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

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
第57行: 第57行:


=== cat ===
=== cat ===
使用 cat 命令
{{shc|<syntaxhighlight lang="bash">
cat node_modules/<pkg>/package.json | grep version</syntaxhighlight>|$|/home/kwy}}
示例
{{Shc_out|<syntaxhighlight lang="bash">
cat node_modules/@postlab/component-rest/package.json | grep version
</syntaxhighlight>|<syntaxhighlight lang="bash">  "version": "0.0.7",
</syntaxhighlight>|$|/home/kwy}}
这种方法不推荐使用,当 cat 路径错误时的异常处理过于繁琐
{{shc|<syntaxhighlight lang="bash">
if (test -a node_modules/<pkg>/package.json); then cat node_modules/<pkg>/package.json | grep version; fi</syntaxhighlight>|$|/home/kwy}}

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

标题文本

查看 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

这种命令式的变体还有:

/home/kwy
echo "console.log(require('./package.json').version);" | node
# or
echo "eval('var result='+require('child_process').execSync('npm version',{encoding:'utf8'})); console.log(result.<pkg>);" | node
# 等

cat

使用 cat 命令

/home/kwy
cat node_modules/<pkg>/package.json | grep version

示例

[jian@kang /home/kwy]$
cat node_modules/@postlab/component-rest/package.json | grep version
  "version": "0.0.7",

这种方法不推荐使用,当 cat 路径错误时的异常处理过于繁琐

/home/kwy
if (test -a node_modules/<pkg>/package.json); then cat node_modules/<pkg>/package.json | grep version; fi