When developing software for Node.js, I use the n package manager to manage and switch between Node versions. Recently, I needed to update my installed Node version (9.2.1) to something more recent. I ran $ sudo n latest to install 13.1.0. But after the upgrade, npm installations stopped working. Any use of npm i would error with:

ERR! Cannot read property 'resolve' of undefined

After extensive research, it turned out this was the result of an incompatibility between old versions of n (<2.1.12) and recent versions of node.

Online forums said the solution was to downgrade back to the older version of Node and be happy with that. I needed the newer Node, so this wasn’t an option. But there was a catch-22: in order to update n to a later version compatible with recent Node, I needed to use npm, which n had broken.

Here are the steps I tried that ended up working.

First I temporarily downgraded Node back to the older version.

$ sudo n

This restored npm to a working version. Then I told the older npm version to upgrade n.

$ sudo npm i -g n
~/npm/bin/n -> ~/npm/lib/node_modules/n/bin/n
+ n@6.1.2
updated 1 package in 2.231s

This should have worked in theory. But when I checked n’s version, it was still the old package.

$ n -V

Because I had seen above where n version 6.1.2 had been installed, I ran the following commands to manually replace the old n with the new n:

$ cd /usr/local/bin
$ sudo rm n
$ sudo ln -s ~/npm/lib/node_modules/n/bin/n n

I confirmed that n was the correct version:

$ n -V

Then I was able to run the new n and install the new Node latest.

$ sudo n latest

Because I was working with a new n, it was able to install new Node correctly. Now npm installs packages without error. Hopefully this helps someone else.