Isolating node_modules in Vagrant

I’m playing with Otto to set up a development environment. Normally, I develop on Mac OS X, but I want to try developing on Linux, to see why the build fails on Travis CI but passes on CircleCI, and if I could do anything about it.

As of writing, Otto uses Vagrant under the hood. For odd reason, I couldn’t get it to work with Parallels. “invalid arch independent ELF magic,” said the console, and I’m stuck with GRUB’s recovery mode or something.

VirtualBox, on the other hand, works fine. So I went ahead with VirtualBox.

The problem comes when I try to npm install.

Lots of weird errors going on.

The /vagrant folder is shared between my Mac and my virtual machine. By extension, this means the node_modules are shared as well.

npm install seems to cause a lot of crazy disk I/O on the shared folder, causing gibberish bytes to be written in some files, causing installation failure.

The solution is to isolate that folder, so that the node_modules folder lives in the VM instead of shared between guest and host. But how do I do it, since npm does not install your dependencies anywhere except in node_modules?

The trick is to use bindfs. Inside the virtual machine, run this command:

$ mkdir ~/vagrant_node_modules
$ sudo mount --bind ~/vagrant_node_modules /vagrant/node_modules

Now, your /vagrant folder is shared, but /vagrant/node_modules is now separated between your host machine and your guest machine.

$ mount
[...]
vagrant on /vagrant type vboxsf (uid=1000,gid=1000,rw)
[...]
/home/vagrant/vagrant_node_modules on /vagrant/node_modules type none (rw,bind)

And now my npm install works fine.