我如何通过命令行参数的Node.js? [英] How do I pass command line arguments to node.js?
问题描述
我已经写在Web服务器的node.js ,我想用一个特定的文件夹来启动。我不知道如何访问在JavaScript中的参数。我运行的节点如下:
$节点server.js文件夹
其中, server.js
是我的code。 Node.js的帮助说,这是可能的:
$节点-h
用法:节点[选项]的script.js [参数]
我将如何使用在JavaScript这些争论?不知怎的,我没能在网上找到这些信息。
标准方法(无库)
该参数存储在 process.argv
process.argv
是包含命令行参数数组。第一元件将是节点,第二个元素将是JavaScript文件的名称。接下来的内容将是任何额外的命令行参数。
块引用>//打印process.argv
process.argv.forEach(功能(VAL,指数,数组){
的console.log(索引+:+ VAL);
});这将产生:
$节点的过程2.js一二=三四
0:节点
1:/Users/mjr/work/node/process-2.js
2:一种
3:二=三个
4:四I have a web server written in node.js that 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
Where
server.js
is my 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.
解决方案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
这篇关于我如何通过命令行参数的Node.js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!