Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a web server written in Node.js and I would like to launch with a specific folder. I'm not sure how to access 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 possible:

$ node -h Usage: node [options] script.js [arguments] 

How would I access those arguments in JavaScript? Somehow I was not able to find this information on the web.

like image 537
milkplus Avatar asked Dec 04 '10 01:12

milkplus


People also ask

What is command line arguments in node JS?

In Node. js, as in C and many related environments, all command-line arguments received by the shell are given to the process in an array called argv (short for 'argument values'). Node.js exposes this array for every running process in the form of process.argv - let's take a look at an example.

How do you pass command line arguments?

To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments.

Which object holds arguments pass through a node command?

The way you retrieve it is using the process object built into Node. js. It exposes an argv property, which is an array that contains all the command line invocation arguments.


1 Answers

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 
like image 145
MooGoo Avatar answered Sep 20 '22 01:09

MooGoo