Javascript 如何将命令行参数传递给 Node.js 程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4351521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:02:47  来源:igfitidea点击:

How do I pass command line arguments to a Node.js program?

javascriptnode.jsargumentscommand-line-arguments

提问by milkplus

I have a web server written in Node.jsand I would like to launch with a specific folder. I'm not sure how to access arguments in JavaScript. I'm running node like this:

我有一个用Node.js编写的 Web 服务器,我想使用特定文件夹启动。我不确定如何在 JavaScript 中访问参数。我正在像这样运行节点:

$ node server.js folder

here server.jsis my server code. Node.js help says this is possible:

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

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

How would I access those arguments in JavaScript? Somehow I was not able to find this information on the web.

我将如何在 JavaScript 中访问这些参数?不知何故,我无法在网上找到这些信息。

回答by MooGoo

Standard Method (no library)

标准方法(无库)

The arguments are stored in process.argv

参数存储在 process.argv

Here are the node docs on handling command line args:

以下是有关处理命令行参数的节点文档:

process.argvis an array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.

process.argv是一个包含命令行参数的数组。第一个元素将是“节点”,第二个元素将是 JavaScript 文件的名称。下一个元素将是任何其他命令行参数。

// print process.argv
process.argv.forEach(function (val, index, array) {
  console.log(index + ': ' + val);
});

This will generate:

这将生成:

$ 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

回答by Mauvis Ledford

To normalize the arguments like a regular javascript function would receive, I do this in my node.js shell scripts:

为了像常规 javascript 函数一样规范化参数,我在我的 node.js shell 脚本中执行此操作:

var args = process.argv.slice(2);

Note that the first arg is usually the path to nodejs, and the second arg is the location of the script you're executing.

请注意,第一个 arg 通常是 nodejs 的路径,第二个 arg 是您正在执行的脚本的位置。

回答by real_ate

The up-to-date rightanswer for this it to use the minimistlibrary. We used to use node-optimistbut it has since been deprecated.

最新的正确答案是使用minimist库。我们曾经使用node-optimist,但它已被弃用。

Here is an example of how to use it taken straight from the minimist documentation:

以下是直接从 minimist 文档中获取的如何使用它的示例:

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' }

回答by dthree

2018 answer based on current trends in the wild:

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



Vanilla javascript argument parsing:

Vanilla javascript 参数解析:

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

This returns:

这将返回:

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

Official docs

官方文档



Most used NPM packages for argument parsing:

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

Minimist: For minimal argument parsing.

Minimist:用于最小参数解析。

Commander.js: Most adopted module for argument parsing.

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

Meow: Lighter alternative to Commander.js

Meow:Commander.js 的轻量级替代品

Yargs: More sophisticated argument parsing (heavy).

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

Vorpal.js: Mature / interactive command-line applications with argument parsing.

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

回答by gor

Optimist (node-optimist)

乐观主义者(节点乐观主义者)

Check out optimist library, it is much better than parsing command line options by hand.

查看optimist library,它比手动解析命令行选项要好得多。

Update

更新

Optimist is deprecated. Try yargswhich is an active fork of optimist.

乐观主义者已被弃用。试试yargs,它是乐观主义者的活跃分支。

回答by Paul van Jaarsveld

Several great answers here, but it all seems very complex. This is very similar to how bash scripts access argument values and it's already provided standard with node.js as MooGoo pointed out. (Just to make it understandable to somebody that's new to node.js)

这里有几个很好的答案,但这一切似乎都很复杂。这与 bash 脚本访问参数值的方式非常相似,并且正如 MooGoo 指出的那样,它已经为 node.js 提供了标准。(只是为了让 node.js 的新手可以理解)

Example:

例子:

$ 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"

回答by balupton

Commander.js

指挥官.js

Works great for defining your options, actions, and arguments. It also generates the help pages for you.

非常适合定义您的选项、操作和参数。它还为您生成帮助页面。

Promptly

及时

Works great for getting input from the user, if you like the callback approach.

如果您喜欢回调方法,非常适合从用户那里获取输入。

Co-Prompt

共同提示

Works great for getting input from the user, if you like the generator approach.

如果您喜欢生成器方法,那么非常适合从用户那里获取输入。

回答by Michael Warner

No Libs with Flags Formatted into a Simple Object

没有带标志的 Libs 被格式化为一个简单的对象

function getArgs () {
    const args = {};
    process.argv
        .slice(2, process.argv.length)
        .forEach( arg => {
        // long arg
        if (arg.slice(0,2) === '--') {
            const longArg = arg.split('=');
            const longArgFlag = longArg[0].slice(2,longArg[0].length);
            const longArgValue = longArg.length > 1 ? longArg[1] : true;
            args[longArgFlag] = longArgValue;
        }
        // flags
        else if (arg[0] === '-') {
            const flags = arg.slice(1,arg.length).split('');
            flags.forEach(flag => {
            args[flag] = true;
            });
        }
    });
    return args;
}
const args = getArgs();
console.log(args);

Examples

例子

Simple

简单的

input

输入

node test.js -D --name=Hello

output

输出

{ D: true, name: 'Hello' }

Real World

真实世界

input

输入

node config/build.js -lHRs --ip=$HOST --port=$PORT --env=dev

output

输出

{ 
  l: true,
  H: true,
  R: true,
  s: true,
  ip: '127.0.0.1',
  port: '8080',
  env: 'dev'
}

回答by sgmonda

Stdio Library

标准库

The easiest way to parse command-line arguments in NodeJS is using the stdiomodule. Inspired by UNIX getoptutility, it is as trivial as follows:

在 NodeJS 中解析命令行参数的最简单方法是使用stdio模块。受 UNIXgetopt实用程序的启发,它很简单,如下所示:

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'}
});

If you run the previous code with this command:

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

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

Then opsobject will be as follows:

那么ops对象将如下:

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

So you can use it as you want. For instance:

所以你可以随意使用它。例如:

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

Grouped options are also supported, so you can write -ominstead of -o -m.

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

Furthermore, stdiocan generate a help/usage output automatically. If you call ops.printHelp()you'll get the following:

此外,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

The previous message is shown also if a mandatory option is not given (preceded by the error message) or if it is mispecified (for instance, if you specify a single arg for an option and it needs 2).

如果未给出强制选项(在错误消息之前)或错误指定(例如,如果您为选项指定单个 arg 而它需要 2),也会显示上一条消息。

You can install stdiomodule using NPM:

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

npm install stdio

回答by Sean H. Worthington

If your script is called myScript.js and you want to pass the first and last name, 'Sean Worthington', as arguments like below:

如果您的脚本名为 myScript.js 并且您希望将名字和姓氏“Sean Worthington”作为参数传递,如下所示:

node myScript.js Sean Worthington

Then within your script you write:

然后在你的脚本中你写:

var firstName = process.argv[2]; // Will be set to 'Sean'
var lastName = process.argv[3]; // Will be set to 'Worthington'