Node.js/npm/版本号码:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
第44行: 第44行:
{{Shc_out|<syntaxhighlight lang="bash">
{{Shc_out|<syntaxhighlight lang="bash">
node -e "try {console.log(require('./node_modules/@postlab/component-rest/package.json').version)} catch (e){''}"
node -e "try {console.log(require('./node_modules/@postlab/component-rest/package.json').version)} catch (e){''}"
</syntaxhighlight>|<syntaxhighlight lang="bash">0.0.7
</syntaxhighlight>|<syntaxhighlight lang="text">0.0.7
</syntaxhighlight>|$|/home/kwy}}
</syntaxhighlight>|$|/home/kwy}}

2025年7月26日 (六) 09:19的版本

标题文本

查看 npm 版本

/home/kwy
npm -v

注册表版本号码

本地版本号码

nodejs

借助 nodejs 可以间接获取本地已安装 pkg 的版本号码。

/home/kwy
node -p "require('./node_modules/<pkg>/package.json').version"
# or
node -e "console.log(require('./node_modules/<pkg>/package.json').version);"

但是这里有一个问题就是当 require 路径错误时会抛出异常,如

node:internal/modules/cjs/loader:1404
  throw err;
  ^
Error: Cannot find module './node_moddules/@postlab/component-rest/package.json'
Require stack:
- /home/kwy/postlab-vip/packages/postlab-common/[eval]
    at Function._resolveFilename (node:internal/modules/cjs/loader:1401:15)
// ...
  requireStack: [ '/home/kwy/postlab-vip/packages/postlab-common/[eval]' ]
}
Node.js v22.17.0

这回影响我们的脚本执行,所以需要异常的捕获处理

/home/kwy
node -p "try {require('./node_modules/<pkg>/package.json').version} catch (e){''}"
# or
node -e "try {console.log(require('./node_modules/<pkg>/package.json').version)} catch (e){''}"

测试

[jian@kang /home/kwy]$
node -e "try {console.log(require('./node_modules/@postlab/component-rest/package.json').version)} catch (e){''}"
0.0.7