npm 命令详解与参数实测(Ubuntu 22.04)

在 Ubuntu 22.04(npm 10.8.2 / Node.js v20.20.2)逐项实测 npm 全流程:init 工程初始化、config 配置与 registry 切换、view 查包、install 真实装包(--save-exact/--save-dev/--dry-run)、ls 依赖树与 package-lock、outdated/update/uninstall、audit 安全审计真实漏洞回显、run 脚本与环境变量注入、exec 按需拉包、cache 缓存、ci 精确重装、pack 打包,含 404/ENEEDAUTH 报错排查与 yarn/pnpm 对照。

Linux命令npmLinux系统UbuntuUbuntu 22.04命令行2026/10/17

npm 命令详解与参数实测(Ubuntu 22.04)

目标:全面掌握 npm 的每一个常用子命令与参数——工程初始化(init/pkg get/pkg set/pkg delete)、配置管理(config get/set/delete/list 与 .npmrc、registry 切换)、registry 查询(view 的 version/dependencies/dist-tags/versions)、依赖管理(install 及 --save-exact/--save-dev/--dry-run、ls 依赖树、outdated/update/uninstall)、安全审计(audit、audit --omit=dev 与真实漏洞回显)、脚本运行(run、--silent、npm 注入的环境变量)、按需执行(exec/npx)、缓存(cache verify 与 _cacache 落盘结构)、精确重装与打包(ci/pack --dry-run),全部命令与回显已在 Ubuntu 22.04(npm 10.8.2)实测通过。

一、环境信息

本文所有命令均在以下环境实测,回显逐字照抄:

  • 操作系统:Ubuntu 22.04.5 LTS(x86_64)
  • npm:10.8.2(随 NodeSource nodejs 包附带,全局位于 /usr/lib/node_modules/npm)
  • Node.js:v20.20.2
  • registry:官方源 https://registry.npmjs.org/(直连可用,另实测 npmmirror 切换)
  • 执行身份:root;演示目录 /opt/npmtest
$ npm --version
10.8.2
exit=0

$ npm -v
10.8.2
exit=0

$ node --version
v20.20.2

$ npm ls -g --depth=0
/usr/lib
+-- corepack@0.34.6
`-- npm@10.8.2

二、命令概览

npm 采用「子命令 + 配置参数」结构,npm <command> -h 可快速查任一子命令帮助:

$ npm --help(截取前 32 行)
npm <command>

Usage:

npm install        install all the dependencies in your project
npm install <foo>  add the <foo> dependency to your project
npm test           run this project's tests
npm run <foo>      run the script named <foo>
npm <command> -h   quick help on <command>
npm -l             display usage info for all commands
npm help <term>    search for help on <term>
npm help npm       more involved overview

All commands:

    access, adduser, audit, bugs, cache, ci, completion,
    config, dedupe, deprecate, diff, dist-tag, docs, doctor,
    edit, exec, explain, explore, find-dupes, fund, get, help,
    help-search, hook, init, install, install-ci-test,
    install-test, link, login, logout, ls, org, outdated,
    owner, pack, ping, pkg, prefix, prune, publish, query,
    rebuild, repo, restart, root, run-script, sbom, search,
    set, shrinkwrap, star, stars, start, stop, team, test,
    token, uninstall, unpublish, unstar, update, version,
    view, whoami

Specify configs in the ini-formatted file:
    /root/.npmrc
or on the command line via: npm <command> --key=value
子命令作用本文小节
npm init -y跳过问答生成 package.json四
npm pkg get/set/delete直接读写 package.json 字段四
npm config get/set/delete/list查改配置(落盘 .npmrc)五
npm view <pkg> [字段]查询 registry 上包的元数据六
npm install [pkg] [flags]安装依赖并写入 package.json七
npm ls [--depth=N] / -g打印依赖树八
npm outdated / update / uninstall过期检查/升级/卸载九
npm audit [--omit=dev]依赖漏洞审计十
npm run <name>执行 package.json 里的脚本十一
npm exec --yes <pkg>按需下载并执行包的 bin(npx 同义)十二
npm cache verify校验并压缩本地缓存十三
npm ci / npm pack --dry-run按 lockfile 精确重装 / 打包预览十四

三、工程初始化:init 与 pkg

npm init -y 跳过交互问答,直接用默认值生成 package.json:

$ npm init -y
Wrote to /opt/npmtest/package.json:

{
  "name": "npmtest",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}
exit=0

npm pkg 是无需jq的 package.json 读写器,get 取值、set 写入、delete 删除:

$ npm pkg get name version
{
  "name": "npmtest",
  "version": "1.0.0"
}

$ npm pkg set scripts.demo='node -e "console.log(6*7)"'
exit=0

$ npm pkg get scripts
{
  "test": "echo \"Error: no test specified\" && exit 1",
  "demo": "node -e \"console.log(6*7)\""
}

$ npm pkg delete scripts.demo

💡 说明: pkg set 支持点路径(scripts.demo、dependencies.lodash),比手工编辑 JSON 不易出语法错误;注意 shell 层的引号——单引号包住整段 JS,内层双引号才不会被剥。

四、配置管理:config 与 .npmrc

$ npm config get registry
https://registry.npmjs.org/

$ npm config get cache
/root/.npm

$ npm config list
; "user" config from /root/.npmrc

; node bin location = /usr/bin/node
; node version = v20.20.2
; cwd = /opt/npmtest
; HOME = /root
; Run `npm config ls -l` to show all defaults.

切源三件套:临时参数级、持久 config set、恢复 config delete:

$ npm view lodash version --registry https://registry.npmmirror.com/(参数级切源)
4.18.1
exit=0

$ npm config set registry https://registry.npmmirror.com/ && npm config get registry
https://registry.npmmirror.com/

$ npm view is-odd version(经 npmmirror 查询)
3.0.1
exit=0

$ npm config delete registry(恢复默认源)
https://registry.npmjs.org/

💡 说明: config set 写入 ~/.npmrc(用户级),优先级为 命令行参数 > 环境变量 > 项目级 .npmrc > 用户级 > 全局级;CI 里推荐命令行参数级切换,不留持久痕迹。

五、registry 查询:view

$ npm view lodash version
4.18.1
exit=0

$ npm view lodash description
Lodash modular utilities.

$ npm view is-odd version dependencies dist-tags
version = '3.0.1'
dependencies = { 'is-number': '^6.0.0' }
dist-tags = { latest: '3.0.1' }

$ npm view chalk versions --json(截取尾部 6 行)
  "5.5.0",
  "5.6.0",
  "5.6.2",
  "6.0.0",
  "6.0.1"
]

💡 说明: view 不落盘、纯查询,写升级脚本时用它取「最新版号」再比较;dist-tags.latest 才是裸 install 会装的版本,不等于 versions 数组最后一项。

六、安装依赖:install 及保存语义

真实装包 is-odd@2.0.0(带传递依赖 is-number):

$ npm install is-odd@2.0.0(真实装包)

added 2 packages, and audited 3 packages in 3s

found 0 vulnerabilities
exit=0

$ cat package.json
{
  "name": "npmtest",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "is-odd": "^2.0.0"
  }
}

$ head -28 package-lock.json
{
  "name": "npmtest",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "npmtest",
      "version": "1.0.0",
      "license": "ISC",
      "dependencies": {
        "is-odd": "^2.0.0"
      }
    },
    "node_modules/is-number": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/is-number/-/is-number-4.0.0.tgz",
      "integrity": "sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ==",
      "license": "MIT",
      "engines": {
        "node": ">=0.10.0"
      }
    },
    "node_modules/is-odd": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/is-odd/-/is-odd-2.0.0.tgz",
      "integrity": "sha512-OTiixgpZAT1M4NHgS5IguFp/Vz2VI3U7Goh4/HA1adtwyLtSBrxYlcSYkhpAE07s4fKEcjrFxyvtQBND4vFQyQ==",
      "license": "MIT",

三种保存语义对比:

$ npm install lodash --save-exact

added 1 package, and audited 4 packages in 3s

found 0 vulnerabilities
exit=0

$ grep -E "lodash|is-odd" package.json
    "is-odd": "^2.0.0",
    "lodash": "4.18.1"

$ npm install --save-dev is-even

added 5 packages, and audited 9 packages in 4s

found 0 vulnerabilities
exit=0

$ cat package.json
{
  "name": "npmtest",
  ...
  "dependencies": {
    "is-odd": "^2.0.0",
    "lodash": "4.18.1"
  },
  "devDependencies": {
    "is-even": "^1.0.0"
  }
}
  • 默认:写入 dependencies,版本带 ^ 前缀(允许小版本/补丁升级)
  • --save-exact(-E):锁定精确版本(无 ^),上例 lodash 固定 4.18.1
  • --save-dev(-D):写入 devDependencies,生产构建(npm install --omit=dev)时跳过

--dry-run 只演算不落盘:

$ npm install --dry-run is-odd(仅演算不落盘)

up to date in 1s
exit=0

七、依赖清单:ls 与依赖树

$ ls node_modules
is-number
is-odd

$ npm ls
npmtest@1.0.0 /opt/npmtest
`-- is-odd@2.0.0

exit=0

$ npm ls --depth=0
npmtest@1.0.0 /opt/npmtest
`-- is-odd@2.0.0

$ npm ls lodash
npmtest@1.0.0 /opt/npmtest
`-- lodash@4.18.1

$ npm ls -g --depth=0(全局已装包)
/usr/lib
+-- corepack@0.34.6
`-- npm@10.8.2

💡 说明: 树形符号 +--/`-- 直接画出了层级;npm ls <pkg> 精确定位某包在哪一层被依赖,排查重复依赖(npm dedupe 的前置动作)靠它。

八、更新与卸载:outdated / update / uninstall

$ npm outdated
Package  Current  Wanted  Latest  Location             Depended by
is-odd     2.0.0   2.0.0   3.0.1  node_modules/is-odd  npmtest
lodash   4.17.15  4.18.1  4.18.1  node_modules/lodash  npmtest
exit=1

四列语义:Current 实装版本、Wanted 按 semver 范围可升到的版本、Latest registry 最新版;有落后项时 outdated 退出码为 1,可直接接进 CI 检查。

$ npm update lodash

changed 1 package, and audited 9 packages in 1s

found 0 vulnerabilities
exit=0

$ npm ls lodash
npmtest@1.0.0 /opt/npmtest
`-- lodash@4.18.1

$ npm uninstall is-even lodash

removed 6 packages, and audited 3 packages in 1s

found 0 vulnerabilities
exit=0

$ npm ls --depth=0
npmtest@1.0.0 /opt/npmtest
`-- is-odd@2.0.0

exit=0

💡 说明: update 只在 semver 允许范围内升(4.17.15 → Wanted 4.18.1);跨大版本(2.0.0 → 3.0.1 这种)必须显式 npm install is-odd@3。outdated 的 Wanted 列就是 update 的终点。

九、安全审计:audit

先降级到一个带已知漏洞的 lodash 版本,触发真实审计回显:

$ npm install lodash@4.17.15(降级到带已知漏洞的版本供 audit 演示)

changed 1 package, and audited 9 packages in 5s

1 high severity vulnerability

To address all issues, run:
  npm audit fix --force

Run `npm audit` for details.
exit=0

$ npm audit
# npm audit report

lodash  <=4.17.23
Severity: high
Command Injection in lodash - https://github.com/advisories/GHSA-35jh-r3h4-6jhm
Prototype Pollution in lodash - https://github.com/advisories/GHSA-p6mc-m468-83gw
Regular Expression Denial of Service (ReDoS) in lodash - https://github.com/advisories/GHSA-29mw-wpgm-hmr9
lodash vulnerable to Code Injection via `_.template` imports key names - https://github.com/advisories/GHSA-r5fr-rjxr-66jc
lodash vulnerable to Prototype Pollution via array path bypass in `_.unset` and `_.omit` - https://github.com/advisories/GHSA-f23m-r3pf-42rh
Lodash has Prototype Pollution Vulnerability in `_.unset` and `_.omit` functions - https://github.com/advisories/GHSA-xxjr-mmjv-4gpg
fix available via `npm audit fix`
node_modules/lodash

1 high severity vulnerability

To address all issues, run:
  npm audit fix
exit=1

$ npm audit --omit=dev
# npm audit report

lodash  <=4.17.23
Severity: high
...
1 high severity vulnerability

To address all issues, run:
  npm audit fix
exit=1

💡 说明: 存在漏洞时 audit 退出码为 1,适合直接放进 CI 门禁;--omit=dev 只审计生产依赖(devDependencies 漏洞不阻断发布流水线),audit fix 会自动升级到无漏洞的兼容版本,--force 才可能跨大版本破坏性升级。

十、运行脚本:run 与环境变量注入

$ npm run(无参数列出 scripts)
Lifecycle scripts included in npmtest@1.0.0:
  test
    echo "Error: no test specified" && exit 1
available via `npm run-script`:
  demo
    node -e "console.log(6*7)"

$ npm run demo

> npmtest@1.0.0 demo
> node -e "console.log(6*7)"

42
exit=0

$ npm run demo --silent
42
exit=0

npm 运行脚本时会注入一批 npm_* 环境变量(实测 npm 10 注入的生命周期变量):

$ npm pkg set scripts.env2="env | grep -E '^npm_(lifecycle|config_registry|package_name)' | head -6"
exit=0

$ npm run env2

> npmtest@1.0.0 env2
> env | grep -E '^npm_(lifecycle|config_registry|package_name)' | head -6

npm_package_name=npmtest
npm_lifecycle_script=env | grep -E '^npm_(lifecycle|config_registry|package_name)' | head -6
npm_lifecycle_event=env2
exit=0

💡 说明: 实测 npm 10.8.2 的 scripts 子进程里有 npm_package_name、npm_lifecycle_event、npm_lifecycle_script,但 npm_config_registry 并未注入——老教程里「在脚本里读 process.env.npm_config_registry 拿当前源」的写法在 npm 10 实测拿到的是 undefined(JSON.stringify({registry: process.env.npm_config_registry}) 输出 {})。要拿 registry 请走 npm config get registry。--silent 抑制 npm 自身的 > 包名 脚本 头两行,只留脚本输出,日志管道里更干净。

十一、按需执行:exec(npx)

npm exec --yes <pkg> [args] 临时下载包、执行其 bin、不写入 dependencies(npx 是它的别名):

$ npm exec --yes cowsay -- hello npm(按需拉包执行)
 ___________
< hello npm >
 -----------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
exit=0

-- 之后是传给包命令的参数;--yes 跳过「需要安装 cowsay,确认吗」的交互提示,CI 里必加。

十二、缓存:cache verify 与落盘结构

$ npm cache verify
Cache verified and compressed (~/.npm/_cacache)
Content verified: 85 (3440923 bytes)
Content garbage-collected: 4 (294234 bytes)
Index entries: 85
Finished in 0.173s

$ ls "$(npm config get cache)/_cacache"(缓存落盘结构)
_lastverified
content-v2
index-v5

缓存命中后重复安装明显提速(added 2 packages ... in 2s)。注意 npm 的缓存目录 ~/.npm/_cacache 是内容寻址存储,手工清缓存用 npm cache clean --force,直接 rm -rf ~/.npm 也会连 token 等一起清掉。

十三、精确重装与打包:ci / pack

npm ci 严格按 package-lock.json 重装(先删 node_modules),版本与 lock 完全一致,CI 流水线的标准动作:

$ rm -rf node_modules && npm ci(按 lockfile 精确重装)

added 2 packages, and audited 3 packages in 2s

found 0 vulnerabilities
exit=0

$ npm ls --depth=0
npmtest@1.0.0 /opt/npmtest
`-- is-odd@2.0.0

$ npm pack --dry-run(打包预览)
npm notice
npm notice package: npmtest@1.0.0
npm notice Tarball Contents
npm notice 383B package.json
npm notice Tarball Details
npm notice name: npmtest
npm notice version: 1.0.0
npm notice filename: npmtest-1.0.0.tgz
npm notice package size: 337 B
npm notice unpacked size: 383 B
npm notice shasum: 4c7fe759d2cc9ea8c548122adb4bb30ccfc4b056
npm notice integrity: sha512-2X00kDyI98hRq[...]ffrXIolf2PnMw==
npm notice total files: 1
npm notice
npmtest-1.0.0.tgz
exit=0

💡 说明: ci 与 install 的差别——ci 不允许 lock 与 package.json 不同步(直接报错退出)、不写入/更新任何文件;pack --dry-run 预览将要发布的 tarball 内容与体积,发布前确认没有把秘钥文件打进去。

十四、常见问题与排查

1. npm error 404 'xxx@*' is not in this registry(退出码 1):包名拼错、私有包未登录、或当前 registry 确实没有该包。先 npm view <pkg> version 验证;换源用 --registry。

$ npm install no-such-pkg-404xyz; echo $?
npm error 404
npm error 404  'no-such-pkg-404xyz@*' is not in this registry.
npm error 404
npm error 404 Note that you can also install from a
npm error 404 tarball, folder, http url, or git url.
npm error A complete log of this run can be found in: /root/.npm/_logs/2026-10-17T03_03_24_029Z-debug-0.log
404-exit=1

2. ENEEDAUTH(whoami/publish 等):需要登录态的命令在未授权时直接拒绝:

$ npm whoami(未登录场景)
npm error code ENEEDAUTH
npm error need auth This command requires you to be logged in.
npm error need auth You need to authorize this machine using `npm adduser`
exit=1

3. npm help <cmd> 报 "This system has been minimized...":最小化系统没有 man 手册。用 npm <command> -h 快速帮助替代,或 apt install man-db 补齐。

4. scripts 里引号被剥、Unexpected end of input:npm 用 shell 解释 scripts 字符串,node -p "a" + b 这类写法外层引号会被 sh 吃掉。用单引号包住整个 JS 表达式:node -p 'JSON.stringify({...})'。

5. 脚本里读不到 npm_config_registry:npm 10 实测不注入该变量(详见十节),别按老教程写。

6. audit 退出码 1 挡住流水线:这是设计行为(有漏洞即失败)。临时豁免用 audit --omit=dev 缩小范围,或升级到 audit fix 能处理的版本。

7. ci 报 lock 不同步:package.json 与 package-lock.json 版本范围冲突,先 npm install 刷新 lock 再 npm ci;lock 文件必须提交进仓库。

十五、与同类包管理器对照

能力npm 10yarn 1/4pnpm 9bun
初始化npm init -yyarn init -ypnpm initbun init
装包npm installyarn add / yarn installpnpm add / pnpm installbun add / bun install
精确重装npm ciyarn install --immutablepnpm install --frozen-lockfilebun install --frozen-lockfile
查包npm viewyarn infopnpm viewbun pm view
审计npm audityarn auditpnpm audit—
运行脚本npm runyarn runpnpm runbun run
按需执行npm exec / npxyarn dlxpnpm dlxbunx

npm 的 ci/audit/exec 三件套与 yarn/pnpm 语义对齐;pnpm 以硬链接省磁盘、bun 以单二进制换速度,但「零配置即用、文档生态最全」仍是 npm 的默认优势——尤其 npm ci 在 CI 环境里开箱可用,不需要额外引导步骤。