在Node.js中,我想读取registrynpm用于确定从何处下载软件包的属性的值。
const registry = someApi.get('registry');
Run Code Online (Sandbox Code Playgroud)
我想知道,以便我可以创建一个预安装脚本,以确保开发人员通过本地Artifactory实例而不是直接从npm.org 下载软件包。
const EXPECTED_REGISTRY = 'https://example.com/artifactory'
const registry = someApi.get('registry');
if (registry !== EXPECTED_REGISTRY) {
console.log('Please configure your .npmrc to use Artifactory');
console.log('See http://example.com/instructions');
process.exit(1);
}
Run Code Online (Sandbox Code Playgroud)
做到这一点的一种方法是掏腰包npm config list --json。必须有一个可以给我相同结果的API。我只是找不到它。
虽然已经有一个可接受的答案,但我将为后代发布一个替代答案。
如果您使用npm命令运行脚本并将脚本添加到package.json文件的scripts属性中,那么NodeJS脚本应该可以通过pattern访问NPM config属性。process.env.npm_config_*
例如,给定以下package.json文件:
{
"scripts": {
"start": "node -p \"process.env.npm_config_foo\""
}
}
Run Code Online (Sandbox Code Playgroud)
运行以下命令时:
npm config set foo bar
npm start
Run Code Online (Sandbox Code Playgroud)
输出为:
> @ start /Users/anonymous/projects/my-package
> node -p "process.env.npm_config_foo"
bar
Run Code Online (Sandbox Code Playgroud)
需要注意的是,如果你的scripts财产是不是NPM著名的特性之一(例如test,start),你需要使用npm run <script-name>代替npm <script-name>。
参考:https : //docs.npmjs.com/misc/config
我很确定你必须“掏钱”,据我所知,没有其他 API。
您可以利用节点的execSync()或exec()方法来执行npm config子命令get,即:
$ npm config get registry
Run Code Online (Sandbox Code Playgroud)
节点示例使用execSync():
const execSync = require('child_process').execSync;
const EXPECTED_REGISTRY = 'https://example.com/artifactory';
const registry = execSync('npm config get registry',
{ stdio: ['ignore', 'pipe', 'pipe'] }).toString().replace(/\n$/, '');
if (registry !== EXPECTED_REGISTRY) {
console.log('Please configure your .npmrc to use Artifactory');
console.log('See http://example.com/instructions');
process.exit(1);
}
Run Code Online (Sandbox Code Playgroud)
笔记:
execSync()选项stdio配置为防止将返回registry值记录到控制台。/\n$/用于删除换行符。| 归档时间: |
|
| 查看次数: |
1417 次 |
| 最近记录: |