1

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

JAN
  • 20,056
  • 54
  • 170
  • 290

3 Answers3

3

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 demo --mail=xyz.com --name=sample

output: send email to sample@xyz.com

2
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
0

Use process.argv to access the arguments in your script.

As for how to specify your arguments, see: Sending command line arguments to npm script

Halcyon
  • 56,029
  • 10
  • 87
  • 125