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

$ node server.js folder

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

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

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


当前回答

npm install ps-grab

如果您想运行以下内容:

node greeting.js --user Abdennour --website http://abdennoor.com 

--

var grab=require('ps-grab');
grab('--username') // return 'Abdennour'
grab('--action') // return 'http://abdennoor.com'

或者类似于:

node vbox.js -OS redhat -VM template-12332 ;

--

var grab=require('ps-grab');
grab('-OS') // return 'redhat'
grab('-VM') // return 'template-12332'

其他回答

命令行参数值得一看!

您可以使用主要符号标准设置选项(了解更多信息)。这些命令都是等效的,设置相同的值:

$ example --verbose --timeout=1000 --src one.js --src two.js
$ example --verbose --timeout 1000 --src one.js two.js
$ example -vt 1000 --src one.js two.js
$ example -vt 1000 one.js two.js

要访问这些值,首先创建一个选项定义列表,描述应用程序接受的选项。type属性是setter函数(提供的值通过该函数传递),使您能够完全控制接收的值。

const optionDefinitions = [
  { name: 'verbose', alias: 'v', type: Boolean },
  { name: 'src', type: String, multiple: true, defaultOption: true },
  { name: 'timeout', alias: 't', type: Number }
]

接下来,使用commandLineArgs()解析选项:

const commandLineArgs = require('command-line-args')
const options = commandLineArgs(optionDefinitions)

选项现在看起来如下:

{
  src: [
    'one.js',
    'two.js'
  ],
  verbose: true,
  timeout: 1000
}

高级用法

除了上述典型用法外,还可以配置命令行参数以接受更高级的语法形式。

基于命令的语法(git样式),格式为:

$ executable <command> [options]

例如

$ git commit --squash -m "This is my commit message"

命令和子命令语法(docker样式),格式如下:

$ executable <command> [options] <sub-command> [options]

例如

$ docker run --detached --image centos bash -c yum install -y httpd

生成使用指南

可以使用命令行用法生成使用指南(通常在设置--help时打印)。请参阅下面的示例并阅读文档以了解如何创建它们。

典型的使用指南示例。

聚合物cli使用指南是一个很好的现实例子。

进一步阅读

还有很多需要学习的内容,请参见wiki获取示例和文档。

Stdio库

在NodeJS中解析命令行参数的最简单方法是使用stdio模块。受UNIX getopt实用程序的启发,它非常简单:

var stdio = require('stdio');
var ops = stdio.getopt({
    'check': {key: 'c', args: 2, description: 'What this option means'},
    'map': {key: 'm', description: 'Another description'},
    'kaka': {args: 1, required: true},
    'ooo': {key: 'o'}
});

如果使用此命令运行前面的代码:

node <your_script.js> -c 23 45 --map -k 23 file1 file2

那么ops对象将如下所示:

{ check: [ '23', '45' ],
  args: [ 'file1', 'file2' ],
  map: true,
  kaka: '23' }

所以你可以随心所欲地使用它。例如:

if (ops.kaka && ops.check) {
    console.log(ops.kaka + ops.check[0]);
}

还支持分组选项,因此您可以编写-om而不是-o-m。

此外,stdio可以自动生成帮助/用法输出。如果调用ops.printHelp(),将得到以下结果:

USAGE: node something.js [--check <ARG1> <ARG2>] [--kaka] [--ooo] [--map]
  -c, --check <ARG1> <ARG2>   What this option means (mandatory)
  -k, --kaka                  (mandatory)
  --map                       Another description
  -o, --ooo

如果未提供强制选项(前面有错误消息)或指定错误(例如,如果为选项指定了一个参数,并且需要2),也会显示上一条消息。

您可以使用NPM安装stdio模块:

npm install stdio

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

您可以使用system.args获取命令行参数。我使用下面的解决方案将参数解析为一个对象,这样我就可以按名称获取所需的参数。

var system = require('system');

var args = {};
system.args.map(function(x){return x.split("=")})
    .map(function(y){args[y[0]]=y[1]});

现在你不需要知道参数的索引。像args.whatever一样使用它

注意:应该使用file.js x=1y=2这样的命名参数这一解决方案。

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

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