我有一个用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中访问这些参数?不知怎么的,我在网上找不到这些信息。
当前回答
传递参数很简单,接收它们只需读取进程即可。argv array Node基本上可以从任何地方访问。但您肯定希望将它们作为键/值对来读取,因此需要编写一段脚本来解释它。
JosephMerdrignac使用reduce发布了一个漂亮的例子,但它依赖于key=value语法,而不是-kvalue和--keyvalue。我把它重写得更丑、更长,以使用第二种标准,我会把它作为答案发布,因为它不适合作为评论。但它确实完成了任务。
const args = process.argv.slice(2).reduce((acc,arg,cur,arr)=>{
if(arg.match(/^--/)){
acc[arg.substring(2)] = true
acc['_lastkey'] = arg.substring(2)
} else
if(arg.match(/^-[^-]/)){
for(key of arg.substring(1).split('')){
acc[key] = true
acc['_lastkey'] = key
}
} else
if(acc['_lastkey']){
acc[acc['_lastkey']] = arg
delete acc['_lastkey']
} else
acc[arg] = true
if(cur==arr.length-1)
delete acc['_lastkey']
return acc
},{})
使用此代码,命令节点script.js alpha beta-charlie delta--echo foxtrot将为您提供以下对象
args = {
"alpha":true,
"beta":true,
"c":true,
"h":true,
"a":true,
"r":true
"l":true,
"i":true,
"e":"delta",
"echo":"foxtrot"
}
其他回答
标准方法(无库)
参数存储在process.argv中
以下是关于处理命令行参数的节点文档:
process.argv是一个包含命令行参数的数组。第一个元素是“node”,第二个元素是JavaScript文件的名称。接下来的元素将是任何其他命令行参数。
// print process.argv
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
});
这将产生:
$ 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为您提供process.argv属性,它是字符串数组,是调用Node时使用的参数。数组的第一个条目是Node可执行文件,第二个条目是脚本的名称。
如果您使用以下参数运行脚本
$ node args.js arg1 arg2
文件:args.js
console.log(process.argv)
您将获得类似数组的
['node','args.js','arg1','arg2']
大多数人都给出了很好的答案。我也想在这里做些贡献。我使用lodash库迭代我们在启动应用程序时传递的所有命令行参数,以提供答案:
// Lodash library
const _ = require('lodash');
// Function that goes through each CommandLine Arguments and prints it to the console.
const runApp = () => {
_.map(process.argv, (arg) => {
console.log(arg);
});
};
// Calling the function.
runApp();
要运行上述代码,只需运行以下命令:
npm install
node index.js xyz abc 123 456
结果将是:
xyz
abc
123
456
为了像常规javascript函数那样规范化参数,我在node.js shell脚本中执行以下操作:
var args = process.argv.slice(2);
注意,第一个参数通常是nodejs的路径,第二个参数是您正在执行的脚本的位置。
Simple+ES6+无依赖项+支持布尔标志
const process = require( 'process' );
const argv = key => {
// Return true if the key exists and a value is defined
if ( process.argv.includes( `--${ key }` ) ) return true;
const value = process.argv.find( element => element.startsWith( `--${ key }=` ) );
// Return null if the key does not exist and a value is not defined
if ( !value ) return null;
return value.replace( `--${ key }=` , '' );
}
输出:
如果使用节点app.js调用,则argv('fo')将返回null如果使用节点app.js--foo调用,则argv('fo')将返回true如果使用节点app.js调用--foo=,则argv('fo')将返回“”如果使用节点app.js--foo=bar调用,则argv('fo')将返回'bar'