10

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
  • 21,236
  • 66
  • 181
  • 318

3 Answers3

18

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

  • I think you forgot an \" at the end and the command name in your example should be `send` instead of `demo`. So: `npm run send --mail=xyz.com --name=sample` – Gh05d Jul 11 '22 at 08:50
7
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
2

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
  • 57,230
  • 10
  • 89
  • 128