问题
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