How do I pass command line arguments to a Node.js program? How do I pass command line arguments to a Node.js program? node.js node.js

How do I pass command line arguments to a Node.js program?


Standard Method (no library)

The arguments are stored in process.argv

Here are the node docs on handling command line args:

process.argv is an array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.

// print process.argvprocess.argv.forEach(function (val, index, array) {  console.log(index + ': ' + val);});

This will generate:

$ node process-2.js one two=three four0: node1: /Users/mjr/work/node/process-2.js2: one3: two=three4: four


To normalize the arguments like a regular javascript function would receive, I do this in my node.js shell scripts:

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

Note that the first arg is usually the path to nodejs, and the second arg is the location of the script you're executing.


The up-to-date right answer for this it to use the minimist library. We used to use node-optimist but it has since been deprecated.

Here is an example of how to use it taken straight from the minimist documentation:

var argv = require('minimist')(process.argv.slice(2));console.dir(argv);

-

$ node example/parse.js -a beep -b boop{ _: [], a: 'beep', b: 'boop' }

-

$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz{ _: [ 'foo', 'bar', 'baz' ],  x: 3,  y: 4,  n: 5,  a: true,  b: true,  c: true,  beep: 'boop' }