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

ID : 242

viewed : 164

Tags : javascriptnode.jsargumentscommand-line-argumentsjavascript





Top 5 Answer for javascript - How do I pass command line arguments to a Node.js program?

vote vote

96

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.argv process.argv.forEach(function (val, index, array) {   console.log(index + ': ' + val); }); 

This will generate:

$ node process-2.js one two=three four 0: node 1: /Users/mjr/work/node/process-2.js 2: one 3: two=three 4: four 
vote vote

85

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.

vote vote

71

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' } 
vote vote

66

2018 answer based on current trends in the wild:


Vanilla javascript argument parsing:

const args = process.argv; console.log(args); 

This returns:

$ node server.js one two=three four ['node', '/home/server.js', 'one', 'two=three', 'four'] 

Official docs


Most used NPM packages for argument parsing:

Minimist: For minimal argument parsing.

Commander.js: Most adopted module for argument parsing.

Meow: Lighter alternative to Commander.js

Yargs: More sophisticated argument parsing (heavy).

Vorpal.js: Mature / interactive command-line applications with argument parsing.

vote vote

54

Optimist (node-optimist)

Check out optimist library, it is much better than parsing command line options by hand.

Update

Optimist is deprecated. Try yargs which is an active fork of optimist.

Top 3 video Explaining javascript - How do I pass command line arguments to a Node.js program?







Related QUESTION?