简体   繁体   中英

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 192.10.10.1. 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);
});

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 192.10.10.1 is going to be:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM