NodeJS使用npm install安装包解决:npm ERR! code ECONNREFUSED,FetchError reason: connect ECONNREFUSED 错误。

错误信息

在 Linux / FreeBSD 系统中使用 npm install安装软件包:

npm install clean-css-cli

提示如下错误信息:

$ npm install clean-css-cli
npm ERR! code ECONNREFUSED
npm ERR! syscall connect
npm ERR! errno ECONNREFUSED
npm ERR! FetchError: request to https://registry.npmjs.org/clean-css-cli failed, reason: connect ECONNREFUSED 104.16.30.34:443
npm ERR!     at ClientRequest.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/minipass-fetch/lib/index.js:130:14)
npm ERR!     at ClientRequest.emit (node:events:517:28)
npm ERR!     at _destroy (node:_http_client:882:13)
npm ERR!     at onSocketNT (node:_http_client:902:5)
npm ERR!     at process.processTicksAndRejections (node:internal/process/task_queues:83:21)
npm ERR!  FetchError: request to https://registry.npmjs.org/clean-css-cli failed, reason: connect ECONNREFUSED 104.16.30.34:443
npm ERR!     at ClientRequest.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/minipass-fetch/lib/index.js:130:14)
npm ERR!     at ClientRequest.emit (node:events:517:28)
npm ERR!     at _destroy (node:_http_client:882:13)
npm ERR!     at onSocketNT (node:_http_client:902:5)
npm ERR!     at process.processTicksAndRejections (node:internal/process/task_queues:83:21) {
npm ERR!   code: 'ECONNREFUSED',
npm ERR!   errno: 'ECONNREFUSED',
npm ERR!   syscall: 'connect',
npm ERR!   address: '104.16.30.34',
npm ERR!   port: 443,
npm ERR!   type: 'system',
npm ERR!   requiredBy: '.'
npm ERR! }
npm ERR! 
npm ERR! If you are behind a proxy, please make sure that the
npm ERR! 'proxy' config is set properly.  See: 'npm help config'

npm ERR! A complete log of this run can be found in: /home/anxin/.npm/_logs/2023-12-14T03_00_53_366Z-debug-0.log

原因分析

104.16.30.34:443对应的npm镜像源是https://registry.npmjs.org/

使用如下代码查看镜像源:

npm config get registry

显示镜像源信息:

https://registry.npmjs.org/

默认情况下registry.npmjs.org在国内不能访问,如果要安装Nodejs 软件包,需要设置国内的镜像源。

解决方法

解决NodeJS使用npm install安装软件包提示的npm ERR! code ECONNREFUSED,FetchError reason: connect ECONNREFUSED 错误需要配置国内NodeJS镜像源。

查看可用镜像源

查看NodeJS的npm的可用镜像源,需要先安装nrm软件包

sudo npm install -g --no-fund nrm

查看可用的NodeJS npm镜像源

nrm ls

显示如下镜像源信息:

  npm ---------- https://registry.npmjs.org/
  yarn --------- https://registry.yarnpkg.com/
* tencent ------ https://mirrors.cloud.tencent.com/npm/
  cnpm --------- https://r.cnpmjs.org/
  taobao ------- https://registry.npmmirror.com/
  npmMirror ---- https://skimdb.npmjs.com/registry/

配置国内镜像源

配置国内镜像源可以使用两种方法:

  • 使用nrm镜像源管理工具
  • npm命令

推荐:使用nrm换源

使用nrm镜像源管理工具更换镜像源 【该方式简单,但是只能使用nrm包含的镜像源】
如下的示例,我为Node JS npm配置淘宝国内镜像源

nrm use taobao

使用npm命令换源

npm命令更换国内镜像源【该方法命令长,但是可以配置自己想用的任意镜像源】
如下的示例,我为Node JS npm配置淘宝国内镜像源

sudo npm config set registry https://registry.npmmirror.com/