Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 788
amone Avatar asked Oct 15 '17 22:10

amone


People also ask

How do you pass arguments to a yarn script?

You can pass additional arguments to your script by passing them after the script name. Running this command will execute jest -o --watch . [script] can also be any locally installed executable that is inside node_modules/. bin/ .

How do I run a node js script?

The usual way to run a Node. js program is to run the globally available node command (once you install Node. js) and pass the name of the file you want to execute. While running the command, make sure you are in the same directory which contains the app.


1 Answers

Use a double dash before arguments:

npm run test -- arg1 arg2 -f --flag2
like image 193
alexmac Avatar answered Oct 10 '22 10:10

alexmac