如何在 WSL 2 中更新 npm Ubuntu

How to update npm in WSL 2 Ubuntu

我正在尝试将 Windows 10 上 Linux 的 Windows 子系统中 运行 的古老 npm 3.5.2 更新到最新版本.

我运行的命令如下:

sudo npm install -g npm@latest

但是,它失败了,我得到的只是以下输出:

WARN engine npm@7.20.5: wanted: {"node":">=10"} (current: {"node":"8.10.0","npm":"3.5.2"})
/usr/local/lib
└── (empty)
sudo apt install wsl
npm ERR! Linux 5.10.16.3-microsoft-standard-WSL2
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "-g" "npm@latest"atest
npm ERR! node v8.10.0
npm ERR! npm  v3.5.2
npm ERR! path /usr/local/lib/node_modules/.staging/@npmcli/ci-detect-c7bf9552
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall rename

npm ERR! enoent ENOENT: no such file or directory, rename '/usr/local/lib/node_modules/.staging/@npmcli/ci-detect-c7bf9552' -> '/usr/local/lib/node_modules/npm/node_modules/@npmcli/ci-detect'
npm ERR! enoent ENOENT: no such file or directory, rename '/usr/local/lib/node_modules/.staging/@npmcli/ci-detect-c7bf9552' -> '/usr/local/lib/node_modules/npm/node_modules/@npmcli/ci-detect'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! Please include the following file with any support request:
npm ERR!     /mnt/d/Summbit/Humanatomy.Web/npm-debug.log
npm ERR! code 1

我不知道 npm 试图告诉我什么。有人知道这里发生了什么吗?

我发现 this 文章详细说明了最终使我能够更新 npm 的步骤。这些是我遵循的步骤:

  1. 步骤:
sudo npm cache clean -f
output:
npm WARN using --force I sure hope you know what you are doing.
  1. 步骤:
sudo npm install -g n
output:
/usr/local/bin/n -> /usr/local/lib/node_modules/n/bin/n
/usr/local/lib
└── n@7.3.1
  1. 步骤:
sudo n stable
output:
  installing : node-v14.17.4
       mkdir : /usr/local/n/versions/node/14.17.4
       fetch : https://nodejs.org/dist/v14.17.4/node-v14.17.4-linux-x64.tar.xz
   installed : v14.17.4 (with npm 6.14.14)

Note: the node command changed location and the old location may be remembered in your current shell.
         old : /usr/bin/node
         new : /usr/local/bin/node
To reset the command location hash either start a new shell, or execute PATH="$PATH"
  1. 步骤:
sudo n latest
output:
  installing : node-v16.6.1
       mkdir : /usr/local/n/versions/node/16.6.1
       fetch : https://nodejs.org/dist/v16.6.1/node-v16.6.1-linux-x64.tar.xz
   installed : v16.6.1 (with npm 7.20.3)
  1. 步骤: 关闭 shell 并打开一个新的
  2. 步骤:
npm --version
output:
7.20.3

有一个解决方法:

npm install -g yarn 
yarn global add npm 
~/.yarn/bin/npm install -g npm

注意事项:

  • 我的 nodejs 是使用 ~/.nvm 下的 nvm 安装的
  • 如果你在 wsl 模式下 运行,你需要关闭 vscode,然后重新启动 bash。 vscode-服务器进程可能持有某些文件。