我有一个用Node.js编写的web服务器,我想用一个特定的文件夹启动。我不知道如何在JavaScript中访问参数。我运行的节点如下:

$ node server.js folder

这里server.js是我的服务器代码。Node.js帮助说这是可能的:

$ node -h
Usage: node [options] script.js [arguments]

如何在JavaScript中访问这些参数?不知怎么的,我在网上找不到这些信息。


当前回答

最新的正确答案是使用最小化库。我们曾经使用节点乐观主义,但现在已经被弃用了。

下面是一个如何直接从最小化文档中使用它的示例:

var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);

-

$ node example/parse.js -a beep -b boop
{ _: [], a: 'beep', b: 'boop' }

-

$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz
{ _: [ 'foo', 'bar', 'baz' ],
  x: 3,
  y: 4,
  n: 5,
  a: true,
  b: true,
  c: true,
  beep: 'boop' }

其他回答

有一个应用程序可以解决这个问题。嗯,模块。嗯,不止一个,可能有几百个。

Yargs是其中一个有趣的,它的文档很好读。

下面是github/npm页面的一个示例:

#!/usr/bin/env node
var argv = require('yargs').argv;
console.log('(%d,%d)', argv.x, argv.y);
console.log(argv._);

输出在这里(它读取带有破折号等的选项,短和长,数字等)。

$ ./nonopt.js -x 6.82 -y 3.35 rum
(6.82,3.35)
[ 'rum' ] 
$ ./nonopt.js "me hearties" -x 0.54 yo -y 1.12 ho
(0.54,1.12)
[ 'me hearties', 'yo', 'ho' ]

这里有几个很好的答案,但似乎都很复杂。这与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"

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

文件: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']);

2018年答案基于当前野外趋势:


Vanilla javascript参数解析:

const args = process.argv;
console.log(args);

这将返回:

$ node server.js one two=three four
['node', '/home/server.js', 'one', 'two=three', 'four']

官方文件


用于参数分析的最常用的NPM包:

Minimist:用于最小参数解析。

Commander.js:参数解析最常用的模块。

喵:Commander.js的更轻替代品

Yargs:更复杂的参数解析(重)。

Vorpal.js:具有参数解析功能的成熟/交互式命令行应用程序。

基于标准输入分析参数(--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"
}