Sending command line arguments to npm script

To send or pass command line arguments to an npm script, you can “use the — syntax followed by your arguments.” You can then access the arguments in the npm script via the process.argv array.

Starting from npm version 2, the ability to pass arguments directly to scripts using the — separator was introduced. This syntax clarifies which arguments are meant for the npm CLI itself and which are intended to be forwarded to the script being run.


npm run <command> [-- <args>]

The — separator separates the params passed to the npm command and the params passed to your script.

Here is the step-by-step guide to pass or send command line arguments to the npm script.

Step 1: Create a simple server.js file

const args = process.argv.slice(2);

console.log('Received arguments:', args);

Step 2: Add a script to your package.json to run server.js

 "scripts": {
   "myscript": "node server.js"

Step 3: Run the script with arguments

npm run myscript -- arg1 arg2 arg3

After executing the command, I get the following output.

Passing command line arguments to npm script

The syntax tells npm to pass the following arguments to the script. Without the –, npm would interpret them as arguments to npm itself, not the script.

Note: This approach works with npm. The method might vary slightly if you’re using another package manager like Yarn.

Related posts

Read Environment Variables in Node.js

Leave a Comment