NPM is incorrect version on latest Ubuntu (18.04) installation
Normal installation would be sudo apt install nodejs
to install Node.js and then sudo apt install npm
to install Node Package Manager. However, upon doing so, npm -v
says 3.5.2
. To upgrade normally, I would do sudo npm install -g npm
, which updates to the latest version (which, at the time of writing this article, is 6.0.1
).
When I do a which npm
, I get /usr/local/bin/npm
, however apt
installs a symlink at /usr/bin/npm
. If I sudo apt purge npm
to remove npm, it still leaves the npm version of npm at /usr/local/bin/npm
, however npm -v
says -bash: /usr/bin/npm: No such file or directory
.
Many articles say to use a PPA to install nodejs, but I think there should be a native way to do this through apt
.
DigitalOcean instructions on installation normally and through PPA: https://www.digitalocean.com/community/tutorials/how-to-install-node-js-on-ubuntu-18-04
TecAdmin instructions on installation through PPA: https://tecadmin.net/install-latest-nodejs-npm-on-ubuntu/
Solution 1:
TLDR: This problem is caused by Bash caching the path of the npm
command, and can be solved by hash -d npm
. You don't even need to deal with apt purge
unless you want to.
Explanation
Here were my steps for getting a new npm
version on Ubuntu. First, do the installation as OP describes:
$ sudo apt-get install npm
(...apt installation of npm was successful...)
$ npm -v
3.5.2
$ command -v npm
/usr/bin/npm
$ sudo npm install -g npm
(...npm installation of npm was successful...so far, so good)
You can see that the new version is already working fine in /usr/local/bin/npm
, but unfortunately the Bash cache still has /usr/bin/npm
:
$ /usr/local/bin/npm -v
6.4.1
$ npm -v
3.5.2
$ command -v npm
/usr/bin/npm
$ type npm
npm is hashed (/usr/bin/npm)
To fix the problem, clear it from the Bash cache (do this in all open shells):
$ hash -d npm
Now the new version works as desired:
$ npm -v
6.4.1
$ command -v npm
/usr/local/bin/npm
Solution 2:
The way I found is to purge npm through sudo apt purge npm
, then simply recreate a symlink to the global installation via ln -s /usr/local/bin/npm /usr/bin/npm
. After that fix, npm -v
returns 6.0.1
as expected.