Pass parameter to npm run "my command" and use that parameter in my functions

Viewed 9773

Consider app.js

const { doCoolStuff } = require("./api/myApi");
// grab param from command line into "myParam"


doCoolStuff(myParam);

... // more code 

And Package.json:

{
  "name": "-------",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "send": "node app.js"
  },
  
  ... 
}

How can we pass parameter to app.js when running npm run send ?

Something like npm run send myEmail@myDomain.com

3 Answers

Npm will parse any argument you pass to the script unless it's passed after -- followed by a space. After npm parses them, they'll be available under npm_config_ in the environment variables.

{
      "scripts": {
        "send": "echo \"send email to $npm_config_name @ $npm_config_mail "
      }
    }

Then run

npm run send --mail=xyz.com --name=sample

output: send email to sample@xyz.com

const params = process.argv.slice(2)

Now this param variable has all the parameters passed with the npm run command.

npm run send myEmail@domain.com

params[0] // this will provide you with the value myEmail@domain.com
Related