Why npm run ‘s node version is different from node -v directly run in the terminal;

0x00

Add test script to my package.json like this:

{
  "scripts": {
    "test": "node -v"
  }
}

0x01

Run with npm, and this is my confusion which needs to solve.

$ npm run test

> xxx@0.0.1-snapshot test
> node -v

v8.17.0

$ node -v
v16.17.0

0x02

I use n to manage my node version. So I try sudo n latest to update npm.

And also try npm i npm -g to update.

All above method doesn’t work.

Even use find to find all System Nodes, but No such node version can be found.

$ find / -name node -maxdepth 8
/usr/local/bin/node
/usr/local/include/node
/usr/local/n/versions/node
/usr/local/n/versions/node/4.9.1/bin/node
/usr/local/n/versions/node/4.9.1/include/node
/usr/local/n/versions/node/17.5.0/bin/node
/usr/local/n/versions/node/17.5.0/include/node
/usr/local/n/versions/node/10.11.0/bin/node
/usr/local/n/versions/node/10.11.0/include/node
/usr/local/n/versions/node/6.14.4/bin/node
/usr/local/n/versions/node/6.14.4/include/node
/usr/local/n/versions/node/6.10.3/bin/node
/usr/local/n/versions/node/6.10.3/include/node
/usr/local/n/versions/node/14.19.0/bin/node
/usr/local/n/versions/node/14.19.0/include/node
/usr/local/n/versions/node/8.10.0/bin/node
/usr/local/n/versions/node/8.10.0/include/node
/usr/local/n/versions/node/18.7.0/bin/node
/usr/local/n/versions/node/18.7.0/include/node
/usr/local/n/versions/node/12.2.0/bin/node
/usr/local/n/versions/node/12.2.0/include/node
/usr/local/n/versions/node/16.3.0/bin/node
/usr/local/n/versions/node/16.3.0/include/node
/usr/local/n/versions/node/16.10.0/bin/node
/usr/local/n/versions/node/16.10.0/include/node
/usr/local/n/versions/node/15.12.0/bin/node
/usr/local/n/versions/node/15.12.0/include/node

0x03

Debug & Find & Slove it

$ where npm
/usr/local/bin/npm

$ ll /usr/local/bin/npm
lrwxr-xr-x  1 root  wheel    38B Aug 17 16:23 /usr/local/bin/npm -> ../lib/node_modules/npm/bin/npm-cli.js

We have NPM source, so can find NPM running node version by debug it with --inspect-brk.

$ node --inspect-brk /usr/local/lib/node_modules/npm/bin/npm-cli.js run test

Yes, the PATH add current node_modules’s bin to it, and the node version is 8.17.0 !!!

$ ./node_modules/.bin/node -v
v8.17.0

0x04

I should thought it earlier! See this for more information