我有一个用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"
}

其他回答

本地实验方法

Nodejs团队在18.3.0和16.17.0版本中添加了util.parseArgs函数。因此,如果您使用这些或更高版本的nodejs,您可以使用本机解决方案解析命令行参数。

文档中的用法示例:

const {parseArgs} = require('node:util');

const args = process.argv;
const options = {
  foo: {
    type: 'boolean',
    short: 'f'
  },
  bar: {
    type: 'string'
  }
};
const {
  values,
  positionals
} = parseArgs({ args, options, allowPositionals: true });

console.log(values);
console.log(positionals);

输出样本:

$ node parseargs.js -f --bar b
[Object: null prototype] { foo: true, bar: 'b' }
[
  '/Users/mbelsky/.nvm/versions/node/v18.12.1/bin/node',
  '/Users/mbelsky/parseargs.js'
]

您可以解析所有参数并检查它们是否存在。

文件:parse-cli-arguments.js:

module.exports = function(requiredArguments){
    var arguments = {};

    for (var index = 0; index < process.argv.length; index++) {
        var re = new RegExp('--([A-Za-z0-9_]+)=([A/-Za-z0-9_]+)'),
            matches = re.exec(process.argv[index]);

        if(matches !== null) {
            arguments[matches[1]] = matches[2];
        }
    }

    for (var index = 0; index < requiredArguments.length; index++) {
        if (arguments[requiredArguments[index]] === undefined) {
            throw(requiredArguments[index] + ' not defined. Please add the argument with --' + requiredArguments[index]);
        }
    }

    return arguments;
}

不仅仅是这样:

var arguments = require('./parse-cli-arguments')(['foo', 'bar', 'xpto']);

项目.js

for(var i=0;i<process.argv.length;i++){
  console.log(process.argv[i]);
}

终端:

nodemon app.js "arg1" "arg2" "arg3"

结果:

0 'C:\\Program Files\\nodejs\\node.exe'
1 'C:\\Users\\Nouman\\Desktop\\Node\\camer nodejs\\proj.js'
2 'arg1' your first argument you passed.
3 'arg2' your second argument you passed.
4 'arg3' your third argument you passed.

解释:

计算机中node.exe的目录(C:\Program Files\nodejs\node.exe)项目文件的目录(项目js)节点(arg1)的第一个参数节点的第二个参数(arg2)节点的第三个参数(arg3)


实际参数从argv数组的第二个索引开始,即process.argv[2]。

以下是我的命名参数的0-dep解决方案:

const args = process.argv
    .slice(2)
    .map(arg => arg.split('='))
    .reduce((args, [value, key]) => {
        args[value] = key;
        return args;
    }, {});

console.log(args.foo)
console.log(args.fizz)

例子:

$ node test.js foo=bar fizz=buzz
bar
buzz

注意:当参数包含=时,这自然会失败。这仅用于非常简单的用途。

在节点代码中需要内置的进程库。

const {argv} = require('process')

用它们的参数运行程序。

$ node process-args.js one two=three four

argv是以下数组:

argv[0] = /usr/bin/node
argv[1] = /home/user/process-args.js
argv[2] = one
argv[3] = two=three
argv[4] = four