简体   繁体   English

如何将参数传递到node.js javascript文件?

[英]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. 我对Node完全陌生,并且我一直在从该站点阅读process api。 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. 我想将参数传递到我的节点脚本中,因此从命令行来看,它看起来像节点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 您的示例来自节点docs ,因此process.argv (argv代表参数vector)为

An array containing the command line arguments. 包含命令行参数的数组。 The first element will be 'node', the second element will be the name of the JavaScript file. 第一个元素是'node',第二个元素是JavaScript文件的名称。 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: 因此connecttoerver.js -ip 192.10.10.1的输出将是:

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. process.argv只是传递给脚本的命令行参数数组。 But the first one is node , second is the filepath and others are arguments passed to the script separated by white space. 但是第一个是node ,第二个是filepath,其他是传递给脚本的参数(由空格分隔)。

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. 这样的库包括参数解析,默认值,需要一些var等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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