【问题标题】:How to pass flags to nodejs application through npm run-script?如何通过 npm run-script 将标志传递给 nodejs 应用程序?
【发布时间】:2018-03-27 09:54:43
【问题描述】:

我有一个通过“npm”命令运行的 NodeJS 文件。我一直在尝试列出所有参数(包括标志)。如果我通过直接调用节点 exe 来运行它,它工作正常,但如果我使用 npm 命令,我无法访问标志。

代码:

console.dir(process.argv);

当我像这样运行文件时,

node file.js arg1 arg2 -f --flag2

我可以得到所有的论点。

[ '/usr/local/bin/node',
  '/.../file.js',
  'arg1',
  'arg2',
  '-f',
  '--flag2' ]

但是如果我在 package.json 文件中添加一个 npm 运行器并尝试使用它运行,我只能获取参数,而不能获取标志。

npm run test arg1 arg2 -f --flag2

结果:

[ '/usr/local/bin/node',
  '/.../file.js',
  'arg1',
  'arg2' ]

package.json 文件:

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

基本上,节点不会将标志传递给正在运行的脚本。有解决方案吗?我的真实项目路径很长,有很多参数,所以我想使用快捷方式来测试它。

【问题讨论】:

    标签: javascript json node.js package.json


    【解决方案1】:

    在参数前使用双破折号:

    npm run test -- arg1 arg2 -f --flag2
    

    【讨论】:

    • 如果你的参数看起来像--reset,你可以使用npm run test -- --reset
    • 我不确定这有多大的不同,但我试图做“npm run ng serve -o”,但为了得到“o”(用于打开一个新的浏览器窗口)识别,我必须像“npm run ng serve -- -o”一样输入它,在“o”前面加上一个破折号而不是一个双破折号。
    猜你喜欢
    • 2017-01-12
    • 2019-02-08
    • 2023-03-16
    • 2019-12-17
    • 1970-01-01
    • 2013-08-19
    • 2016-05-09
    • 1970-01-01
    • 2019-07-08
    相关资源
    最近更新 更多