Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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

I have a webserver written in Node.js and I might want to dispatch with a particular folder. I don't know how to get to arguments in JavaScript. I'm running node like this:
$ node server.js folder

here server.js is my server code. Node.js help says this is conceivable:
$ node -h
Usage: node [options] script.js [arguments]

How might I get to those arguments in JavaScript? Some way or another I couldn't discover this data on the web.
by

3 Answers

akshay1995
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.
RoliMishra
We can use the minimist library.

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' }
sandhya6gczb
proccess.argv is an array containing command-line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next element will be any additional command-line arguments.

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

Login / Signup to Answer the Question.