Sending command line arguments to npm script

Viewed 795547

The scripts portion of my package.json currently looks like this:

"scripts": {
    "start": "node ./script.js server"
}

...which means I can run npm start to start the server. So far so good.

However, I would like to be able to run something like npm start 8080 and have the argument(s) passed to script.js (e.g. npm start 8080 => node ./script.js server 8080). Is this possible?

20 Answers

I had been using this one-liner in the past, and after a bit of time away from Node.js had to try and rediscover it recently. Similar to the solution mentioned by @francoisrv, it utilizes the npm_config_* variables.

Create the following minimal package.json file:

{
  "name": "argument",
  "version": "1.0.0",
  "scripts": {
    "argument": "echo \"The value of --foo is '${npm_config_foo}'\""
  }
}

Run the following command:

npm run argument --foo=bar

Observe the following output:

The value of --foo is 'bar'

All of this is nicely documented in the npm official documentation:

Note: The Environment Variables heading explains that variables inside scripts do behave differently to what is defined in the documentation. This is true when it comes to case sensitivity, as well whether the argument is defined with a space or equals sign.

Note: If you are using an argument with hyphens, these will be replaced with underscores in the corresponding environment variable. For example, npm run example --foo-bar=baz would correspond to ${npm_config_foo_bar}.

Note: For non-WSL Windows users, see @Doctor Blue's comments below... TL;DR replace ${npm_config_foo} with %npm_config_foo%.

Most of the answers above cover just passing the arguments into your NodeJS script, called by npm. My solution is for general use.

Just wrap the npm script with a shell interpreter (e.g. sh) call and pass the arguments as usual. The only exception is that the first argument number is 0.

For example, you want to add the npm script someprogram --env=<argument_1>, where someprogram just prints the value of the env argument:

package.json

"scripts": {
  "command": "sh -c 'someprogram --env=$0'"
}

When you run it:

% npm run -s command my-environment
my-environment

For PowerShell users on Windows

The accepted answer did not work for me with npm 6.14. Neither adding no -- nor including it once does work. However, putting -- twice or putting "--" once before the arguments does the trick. Example:

npm run <my_script> -- -- <my arguments like --this>

Suspected reason

Like in bash, -- instructs PowerShell to treat all following arguments as literal strings, and not options (E.g see this answer). The issues seems to be that the command is interpreted one time more than expected, loosing the '--'. For instance, by doing

npm run <my_script> -- --option value

npm will run

<my_script> value

However, doing

npm run <my_script> "--" --option value

results in

<my_script> "--option" "value"

which works fine.

I've found this question while I was trying to solve my issue with running sequelize seed:generate cli command:

node_modules/.bin/sequelize seed:generate --name=user

Let me get to the point. I wanted to have a short script command in my package.json file and to provide --name argument at the same time

The answer came after some experiments. Here is my command in package.json

"scripts: {
  "seed:generate":"NODE_ENV=development node_modules/.bin/sequelize seed:generate"
}

... and here is an example of running it in terminal to generate a seed file for a user

> yarn seed:generate --name=user

> npm run seed:generate -- --name=user

FYI

yarn -v
1.6.0

npm -v
5.6.0

Note: This approach modifies your package.json on the fly, use it if you have no alternative.

I had to pass command line arguments to my scripts which were something like:

"scripts": {
    "start": "npm run build && npm run watch",
    "watch": "concurrently  \"npm run watch-ts\" \"npm run watch-node\"",
    ...
}

So, this means I start my app with npm run start.

Now if I want to pass some arguments, I would start with maybe:

npm run start -- --config=someConfig

What this does is: npm run build && npm run watch -- --config=someConfig. Problem with this is, it always appends the arguments to the end of the script. This means all the chained scripts don't get these arguments(Args maybe or may not be required by all, but that's a different story.). Further when the linked scripts are called then those scripts won't get the passed arguments. i.e. The watch script won't get the passed arguments.

The production usage of my app is as an .exe, so passing the arguments in the exe works fine but if want to do this during development, it gets problamatic.

I couldn't find any proper way to achieve this, so this is what I have tried.

I have created a javascript file: start-script.js at the parent level of the application, I have a "default.package.json" and instead of maintaining "package.json", I maintain "default.package.json". The purpose of start-script.json is to read default.package.json, extract the scripts and look for npm run scriptname then append the passed arguments to these scripts. After this, it will create a new package.json and copy the data from default.package.json with modified scripts and then call npm run start.

const fs = require('fs');
const { spawn } = require('child_process');

// open default.package.json
const defaultPackage = fs.readFileSync('./default.package.json');
try {
    const packageOb = JSON.parse(defaultPackage);
    // loop over the scripts present in this object, edit them with flags
    if ('scripts' in packageOb && process.argv.length > 2) {

        const passedFlags = ` -- ${process.argv.slice(2).join(' ')}`;
        // assuming the script names have words, : or -, modify the regex if required.
        const regexPattern = /(npm run [\w:-]*)/g;
        const scriptsWithFlags = Object.entries(packageOb.scripts).reduce((acc, [key, value]) => {
            const patternMatches = value.match(regexPattern);
            // loop over all the matched strings and attach the desired flags.
            if (patternMatches) {
                for (let eachMatchedPattern of patternMatches) {
                    const startIndex = value.indexOf(eachMatchedPattern);
                    const endIndex = startIndex + eachMatchedPattern.length;
                    // save the string which doen't fall in this matched pattern range.
                    value = value.slice(0, startIndex) + eachMatchedPattern + passedFlags + value.slice(endIndex);
                }
            }
            acc[key] = value;
            return acc;
        }, {});
        packageOb.scripts = scriptsWithFlags;
    }

    const modifiedJSON = JSON.stringify(packageOb, null, 4);
    fs.writeFileSync('./package.json', modifiedJSON);

    // now run your npm start script
    let cmd = 'npm';
    // check if this works in your OS
    if (process.platform === 'win32') {
        cmd = 'npm.cmd';    // https://github.com/nodejs/node/issues/3675
    }
    spawn(cmd, ['run', 'start'], { stdio: 'inherit' });

} catch(e) {
    console.log('Error while parsing default.package.json', e);
}

Now, instead of doing npm run start, I do node start-script.js --c=somethis --r=somethingElse

The initial run looks fine, but haven't tested thoroughly. Use it, if you like for you app development.

I find it's possible to just pass variables exactly as you would to Node.js:

// index.js
console.log(process.env.TEST_ENV_VAR)
// package.json
...
"scripts": { "start": "node index.js" },
...
TEST_ENV_VAR=hello npm start

Prints out "hello"

I know there is an approved answer already, but I kinda like this JSON approach.

npm start '{"PROJECT_NAME_STR":"my amazing stuff", "CRAZY_ARR":[0,7,"hungry"], "MAGICAL_NUMBER_INT": 42, "THING_BOO":true}';

Usually I have like 1 var I need, such as a project name, so I find this quick n' simple.

Also I often have something like this in my package.json

"scripts": {
    "start": "NODE_ENV=development node local.js"
}

And being greedy I want "all of it", NODE_ENV and the CMD line arg stuff.

You simply access these things like so in your file (in my case local.js)

console.log(process.env.NODE_ENV, starter_obj.CRAZY_ARR, starter_obj.PROJECT_NAME_STR, starter_obj.MAGICAL_NUMBER_INT, starter_obj.THING_BOO);

You just need to have this bit above it (I'm running v10.16.0 btw)

var starter_obj = JSON.parse(JSON.parse(process.env.npm_config_argv).remain[0]);

Anyhoo, question already answered. Thought I'd share, as I use this method a lot.

I settled for something like this, look at the test-watch script:

"scripts": {
    "dev": "tsc-watch --onSuccess \"node ./dist/server.js\"",
    "test": "tsc && cross-env NODE_OPTIONS=--experimental-vm-modules NODE_NO_WARNINGS=1 jest",
    "test-watch": "cross-env NODE_OPTIONS=--experimental-vm-modules NODE_NO_WARNINGS=1 tsc-watch --onSuccess",
  },

You invoke the test-watch script like this:

// Run all tests with odata in their name
npm run test-watch "jest odata"

npm run script_target -- < argument > Basically this is the way of passing the command line arguments but it will work only in case of when script have only one command running like I am running a command i.e. npm run start -- 4200

"script":{
       "start" : "ng serve --port="
 }

This will run for passing command line parameters but what if we run more then one command together like npm run build c:/workspace/file

"script":{
       "build" : "copy c:/file <arg> && ng build"
 } 

but it will interpreter like this while running copy c:/file && ng build c:/work space/file and we are expected something like this copy c:/file c:/work space/file && ng build

Note :- so command line parameter only work ad expected in case of only one command in a script.

I read some answers above in which some of them are writing that you can access the command line parameter using $ symbol but this will not gonna work

Try cross-env NPM package.

Easy to use. Easy to install. Cross all platform.

Example:

  1. set arguments for command
// package.json
"scripts": {
  “test”: “node test.js”,
  “test-with-env-arg”: “cross-env YourEnvVarName=strValue yarn test,
}
  1. get arguments from process.env
// test.js
const getCommandLineArg = Boolean(process.env.YourEnvVarName === 'true')  // Attention: value of process.env.* is String type, not number || boolean

i had the same issue when i need to deploy to different environments here is the package.json pre and post the updates.

 scripts:
{"deploy-sit": "sls deploy --config resources-sit.yml",
 "deploy-uat": "sls deploy --config resources-uat.yml",
 "deploy-dev": "sls deploy --config resources-dev.yml"}

but here is the correct method to adopt the environment variables rather than repeating ourselves

scripts:{"deploy-env": "sls deploy --config resources-$ENV_VAR.yml"}

finally you can deploy by running ENV_VAR=dev npm run deploy-env

Related