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

$ node server.js folder

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

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

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


当前回答

没有库的TypeScript解决方案:

interface IParams {
  [key: string]: string
}

function parseCliParams(): IParams {
  const args: IParams = {};
  const rawArgs = process.argv.slice(2, process.argv.length);
  rawArgs.forEach((arg: string, index) => {
    // Long arguments with '--' flags:
    if (arg.slice(0, 2).includes('--')) {
      const longArgKey = arg.slice(2, arg.length);
      const longArgValue = rawArgs[index + 1]; // Next value, e.g.: --connection connection_name
      args[longArgKey] = longArgValue;
    }
    // Shot arguments with '-' flags:
    else if (arg.slice(0, 1).includes('-')) {
      const longArgKey = arg.slice(1, arg.length);
      const longArgValue = rawArgs[index + 1]; // Next value, e.g.: -c connection_name
      args[longArgKey] = longArgValue;
    }
  });
  return args;
}

const params = parseCliParams();
console.log('params: ', params);

输入:ts node index.js-p param--参数参数

输出:{p:“param”,参数:“parameter”}

其他回答

使用最小npm包。这是最简单的方法,不需要担心任何事情。

const arguments = require("minimist")(process.argv.slice(2)); 
// get the extra argument of command line . 
eg node app.js --process="sendEmailWithReminder"

我们也可以在windows任务调度程序中使用它。

命令行参数值得一看!

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

$ 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获取示例和文档。

大多数人都给出了很好的答案。我也想在这里做些贡献。我使用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

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

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

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

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