How to pass flags to nodejs application through npm run-script?

ⅰ亾dé卋堺 提交于 2020-01-14 07:26:28

问题


I've a NodeJS file that I run via an "npm" command. I've been trying to list all arguments (including flags). If I run it by directly calling the node exe, it works fine but if I use the npm command, I cannot access the flags.

Code:

console.dir(process.argv);

When I run the file like this,

node file.js arg1 arg2 -f --flag2

I can get all of the arguments.

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

But if I add an npm runner to the package.json file and try to run with it, I can only get the arguments but not the flags.

npm run test arg1 arg2 -f --flag2

The result:

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

package.json file:

{
  "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"
}

Basically, node won't pass flags to the running script. Is there a solution for this? My real project has a long path with a lot of arguments so I want to use a shortcut to test it.


回答1:


Use a double dash before arguments:

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


来源:https://stackoverflow.com/questions/46760799/how-to-pass-flags-to-nodejs-application-through-npm-run-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!