justZito justZito -4 years ago 146
Javascript Question

How can I pass arguments into node.js javascript file?

I am totally new to node and I have been reading the process api from the site. However I do not think I have the context down yet so any help on getting a better understanding.

I want to pass an argument into my node script, so from the command line it would look like node connecttoerver.js -ip I have the code below that kind of works but even reading the docs I do not know what is going on here.

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

Answer Source

Your example is from the node docs, so the process.argv (argv stands for arguments vector) 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.

so the output for connecttoerver.js -ip is going to be:

0: node
1: path/to/connecttoerver.js
2: --=ip

process.argv is just an array of command line arguments passed to the script. But the first one is node, second is the filepath and others are arguments passed to the script separated by white space.

What you really want is a library which could parse the arguments and pass it to you in a handy way. For example with optimist you'll get:

 var argv = require('optimist').argv;

 if (argv.rif - 5 * argv.xup > 7.138) {
    console.log('Test one');
 } else {
    console.log('Test two');

Call it like

node xup.js --rif=55 --xup=9.52
   Test one

node xup.js --rif 12 --xup 8.1
   Test two

Such libraries include argument parsing, default values, making some var required, etc.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download