我有一个用Node.js编写的web服务器,我想用一个特定的文件夹启动。我不知道如何在JavaScript中访问参数。我运行的节点如下:
$ node server.js folder
这里server.js是我的服务器代码。Node.js帮助说这是可能的:
$ node -h
Usage: node [options] script.js [arguments]
如何在JavaScript中访问这些参数?不知怎么的,我在网上找不到这些信息。
我有一个用Node.js编写的web服务器,我想用一个特定的文件夹启动。我不知道如何在JavaScript中访问参数。我运行的节点如下:
$ node server.js folder
这里server.js是我的服务器代码。Node.js帮助说这是可能的:
$ node -h
Usage: node [options] script.js [arguments]
如何在JavaScript中访问这些参数?不知怎么的,我在网上找不到这些信息。
当前回答
如果您的脚本名为myScript.js,并且希望将名和姓“Sean Worthington”作为如下参数传递:
node myScript.js Sean Worthington
然后在脚本中写下:
var firstName = process.argv[2]; // Will be set to 'Sean'
var lastName = process.argv[3]; // Will be set to 'Worthington'
其他回答
如节点文档中所述process.argv属性返回一个数组,其中包含Node.js进程启动时传递的命令行参数。
例如,假设process-args.js的脚本如下:
// print process.argv
process.argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});
以如下方式启动Node.js进程:
$ node process-args.js one two=three four
将生成输出:
0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four
这里有几个很好的答案,但似乎都很复杂。这与bash脚本访问参数值的方式非常相似,正如MooGoo所指出的,node.js已经为其提供了标准。(只是为了让node.js新手能够理解)
例子:
$ node yourscript.js banana monkey
var program_name = process.argv[0]; //value will be "node"
var script_path = process.argv[1]; //value will be "yourscript.js"
var first_value = process.argv[2]; //value will be "banana"
var second_value = process.argv[3]; //value will be "monkey"
NodeJS公开了一个名为process的全局变量。
我们可以使用:
process.argv
获取传递给脚本的命令行参数。
process.argv的输出将是以下顺序的列表:
[
full-path-to-node-executable,
full-path-to-the-script-file
...additonal-arguments-we-provide
]
基于标准输入分析参数(--key=value)
const argv = (() => {
const arguments = {};
process.argv.slice(2).map( (element) => {
const matches = element.match( '--([a-zA-Z0-9]+)=(.*)');
if ( matches ){
arguments[matches[1]] = matches[2]
.replace(/^['"]/, '').replace(/['"]$/, '');
}
});
return arguments;
})();
命令示例
node app.js --name=stackoverflow --id=10 another-argument --text="Hello World"
argv的结果:console.log(argv)
{
name: "stackoverflow",
id: "10",
text: "Hello World"
}
使用最小npm包。这是最简单的方法,不需要担心任何事情。
const arguments = require("minimist")(process.argv.slice(2));
// get the extra argument of command line .
eg node app.js --process="sendEmailWithReminder"
我们也可以在windows任务调度程序中使用它。