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

mil*_*lus 2280 javascript arguments command-line-arguments node.js

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

$ node server.js folder
Run Code Online (Sandbox Code Playgroud)

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

$ node -h
Usage: node [options] script.js [arguments]
Run Code Online (Sandbox Code Playgroud)

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

Moo*_*Goo 2914

标准方法(无库)

参数存储在 process.argv

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

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

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

这将产生:

$ 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
Run Code Online (Sandbox Code Playgroud)

  • 更新:我找到了上述问题的答案.http://stackoverflow.com/questions/12925802/run-a-node-js-script-with-command-line-arguments/12925835#12925835 (8认同)
  • 2023 年,节点运行时的新手,必须在 2016 年、2018 年浏览这些答案,许多人声称这是“新方式”。 2023 年的 TLDR 看起来像:这个答案一直是正确的,其中只有 2 个陷阱您有两个需要忽略的参数;它不会捕获输入到 node.exe 中/之前的参数,例如 --harmony node.exe - 但没关系,您可以在其他地方获取这些参数。其他值得注意的答案是可以更好地解析输入参数并且可提取的库。极简主义就是其中之一,它不再受到支持,但现在它似乎又在另一个仓库中复活了。 (7认同)
  • 我应该在命令提示符下键入什么来运行带有命令行参数的node.js脚本? (6认同)
  • 第二个元素(process.argv [1])可能是也可能不是js文件.node命令语法是**`node [options] [-e script | script.js] [arguments]`**或**`node debug script.js [arguments]`**.例如:`node --harmony script.js balala`或`node --no-deprecation --enable-ssl2 script.js balala`,我们可以使用[**process.execArgv**](https:// nodejs .org/docs/latest/api/process.html #process_process_execargv)与[process.argv](https://nodejs.org/docs/latest/api/process.html#process_process_argv) (5认同)
  • 根据 Node.js 文档,process.argv 不会返回那些特定于 Node.js 的标志。就像你的例子中的“--harmony” (5认同)
  • 当你知道它的位置时,你也可以访问一个参数:`process.argv [n]`其中`n`是从零开始的索引 (4认同)
  • [Minimist](https://www.npmjs.org/package/minimist)是一个非常简单的参数解析器 (2认同)

Mau*_*ord 636

要像普通的javascript函数那样规范化参数,我会在node.js shell脚本中执行此操作:

var args = process.argv.slice(2);
Run Code Online (Sandbox Code Playgroud)

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

  • `var args = process.argv.splice(process.execArgv.length + 2);`//因为有节点命令用法的例外,例如:`node --harmony script.js balala`.见[process.execArgv](https://nodejs.org/docs/latest/api/process.html#process_process_execargv) (50认同)
  • @cuixiping但``execArgv`在`argv`中是_not_所以2就足够了 (32认同)
  • 只是说明我4年前写过这个答案,我正在运行的代码今天仍然运行100%.仍然保持最新的节点版本和仍然零问题:它只是一个简单的shell脚本家伙.不是充满JS库的大型全局对象的一部分.我今天仍然支持我的回答.我将在4年后再发一次更新. (13认同)
  • **请勿`process.argv.splice(process.execArgv.length + 2)`****:对于命令`node --harmony script.js --version`,`process.argv`为`['/ usr / local / bin / node”,“ script.js”,“-version”]。['node。上的标记不包含在`process.argv`中!!](https://nodejs.org/docs/latest/api/process.html#process_process_execargv) (8认同)
  • 在查看了这个答案的编辑历史之后,我想花一点时间来同情@MauvisLedford.没有什么比以个人偏好的名义对您的代码进行未经请求的编辑更令人讨厌(没有可量化的好处,无法启动).这样做的人:抛弃. (7认同)
  • 谢谢Jaseem.很想知道未来规范中的写法.它会打破这么多的js库...... (6认同)
  • 嘿@MauvisLedford已经四年了。我希望有更新! (6认同)
  • 对于那些从良好编程实践的有限经验来到这里的人来说,用代表内置语言结构的相同单词命名变量并不是一个好主意.此外,我们作为程序员的工作是编写_correct_代码.其他所有东西都排在第二位,我认为这是显而易见的. (4认同)
  • @MauvisLedford大声笑我称之为顽固.`args`更短,不会与内置插件冲突.有什么不喜欢的?只是说'啊好小费我没有意识到'并且完成它:) (4认同)
  • 严格模式是完全可选的操作上下文,而不是该语言的新版本.我已经为生产网站编写了很长时间的JavaScript代码,从未遇到过这方面的问题,也不会因为JavaScript的重大变化而导致我的代码有一天破坏 - 这是我们向后兼容的开放式网络从头开始.这就是为什么我的Geocities网站今天仍然看起来很糟糕.对我来说,这几乎是扶手椅的假肢.但是,我默认如果您使用Strict,则更改名称.原谅我,因为我更简单而不是"正确". (2认同)

rea*_*ate 332

最新的正确答案,它使用最小化库.我们曾经使用node-optimist但它已被弃用.

以下是直接从最小化文档中使用它的示例:

var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);
Run Code Online (Sandbox Code Playgroud)

-

$ node example/parse.js -a beep -b boop
{ _: [], a: 'beep', b: 'boop' }
Run Code Online (Sandbox Code Playgroud)

-

$ 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' }
Run Code Online (Sandbox Code Playgroud)

  • 实际上,这个解决方案对于开发具有更多标志和参数的命令行工具更有帮助,并且应该被更多恕我直言. (30认同)
  • 如果您要使用这个答案,请考虑使用更活跃的分叉,[minimist-lite](https://github.com/meszaros-lajos-gyorgy/minimist-lite),因为前者已被放弃。“最新的正确答案”是使用“process.argv.slice(2)”,这是实际问题的答案...... (8认同)
  • @MaxWaterman:因为以单个破折号开头的选项只能用于单个字符.将单个char选项后面的任何内容作为选项的参数(不需要空格).用两个短划线(即--n5)启动选项应该产生'n5:true'.对于大多数Unix命令行工具来说,这是相当标准的行为(但不幸的是,不是全部). (7认同)
  • @JKABC我不会称这是最正确的答案,因为OP只是要求访问简单的命令行信息.但我同意,如果您计划扩展CLI,则minimist和命令行参数都非常有用. (4认同)
  • Imo,这是https://www.npmjs.com/package/command-line-args的一个更简单的替代方案 (2认同)
  • 我想知道为什么'-n5'不会产生'n5:true' - 这对我来说很有意义. (2认同)
  • 这个答案很好。* 2015年8月29日最新提交4cf45a2 * (2认同)

dth*_*ree 297

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


Vanilla javascript参数解析:

const args = process.argv;
console.log(args);
Run Code Online (Sandbox Code Playgroud)

返回:

$ node server.js one two=three four
['node', '/home/server.js', 'one', 'two=three', 'four']
Run Code Online (Sandbox Code Playgroud)

官方文档


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

Minimist:用于最小化参数解析.

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

:Commander.js的替代品

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

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

  • "$ npm install -g yargs"产生了1.9 MB的JavaScript代码.当argv解析器库需要两兆字节的代码时,这种疯狂何时会结束?增加攻击面,浪费RAM等...... (74认同)
  • Yargs是一个更大的工具,也恰好解析命令行参数.没有疯狂,只缺乏信息.如果你想要更轻松的东西,可以使用原始的JS,Meow或Minimist. (8认同)
  • 我创建了一个名为[wily-cli](https://www.npmjs.com/package/wily-cli)的软件包,目的是制作一个比大的更强大,更可定制,更易于使用的工具列出的名字.对于那些感兴趣的人,安装时只有94.6 KB (3认同)

gor*_*gor 122

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

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

更新

Optimist已被弃用.尝试yargs,这是乐观主义者的活跃分支.

  • 这已被弃用.Yargs是一个乐观主义者的分支.https://github.com/chevex/yargs (30认同)
  • +1链接.https://github.com/joyent/node/wiki/modules#wiki-parsers-commandline上有很长的命令行选项解析器列表 (18认同)
  • [Minimist](https://www.npmjs.com/package/minimist)是现已弃用的乐观主义者的另一个接班人.它是"乐观主义者的论证解析者的胆量,没有所有幻想的装饰." 上个月有2300万次下载(截至2015年12月). (7认同)

Pau*_*eld 92

这里有几个很好的答案,但这一切似乎都非常复杂.这与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"
Run Code Online (Sandbox Code Playgroud)


bal*_*ton 79

Commander.js

适用于定义选项,操作和参数.它还会为您生成帮助页面.

及时

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

联合提示

如果您喜欢发电机方法,那么非常适合从用户那里获得输入.

  • @Evan Carroll请不要编辑我的答案来推广图书馆我不使用http://stackoverflow.com/posts/7483600/revisions,特别是因为您缺少的功能,这些意见应该保存以供评论或者向模块作者提出请求,而不是编辑其他人的答案. (23认同)

And*_*dri 50

简单+ES6+无依赖+支持布尔标志

const process = require( 'process' );

const argv = key => {
  // Return true if the key exists and a value is defined
  if ( process.argv.includes( `--${ key }` ) ) return true;

  const value = process.argv.find( element => element.startsWith( `--${ key }=` ) );

  // Return null if the key does not exist and a value is not defined
  if ( !value ) return null;
  
  return value.replace( `--${ key }=` , '' );
}
Run Code Online (Sandbox Code Playgroud)

输出:

  • 如果调用node app.jsthenargv('foo')将返回null
  • 如果调用node app.js --foothenargv('foo')将返回true
  • 如果调用node app.js --foo=thenargv('foo')将返回''
  • 如果调用node app.js --foo=barthenargv('foo')将返回'bar'

  • @temporary_user_name 一切都好...让读者看到 ES6 语法糖和功能的权衡是有好处的...简短明了并不总是等于可读:P (2认同)

Sea*_*ton 46

如果您的脚本名为myScript.js,并且您想要传递名字和名字'Sean Worthington',如下所示:

node myScript.js Sean Worthington
Run Code Online (Sandbox Code Playgroud)

然后在你的脚本中你写:

var firstName = process.argv[2]; // Will be set to 'Sean'
var lastName = process.argv[3]; // Will be set to 'Worthington'
Run Code Online (Sandbox Code Playgroud)


sgm*_*nda 45

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, mandatory: true},
    'ooo': {key: 'o'}
});
Run Code Online (Sandbox Code Playgroud)

如果使用此命令运行上一代码:

node <your_script.js> -c 23 45 --map -k 23 file1 file2
Run Code Online (Sandbox Code Playgroud)

然后ops对象将如下:

{ check: [ '23', '45' ],
  args: [ 'file1', 'file2' ],
  map: true,
  kaka: '23' }
Run Code Online (Sandbox Code Playgroud)

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

if (ops.kaka && ops.check) {
    console.log(ops.kaka + ops.check[0]);
}
Run Code Online (Sandbox Code Playgroud)

也支持分组选项,因此您可以编写-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
Run Code Online (Sandbox Code Playgroud)

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

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

npm install stdio
Run Code Online (Sandbox Code Playgroud)

  • 根据SO的TOS,值得一提的是@sgmonda是模块的唯一维护者;)不错的小模块.绝对有用. (3认同)

Mic*_*ner 41

没有将标志格式化为简单对象的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);
Run Code Online (Sandbox Code Playgroud)

例子

简单

输入

node test.js -D --name=Hello
Run Code Online (Sandbox Code Playgroud)

产量

{ D: true, name: 'Hello' }
Run Code Online (Sandbox Code Playgroud)

真实世界

输入

node config/build.js -lHRs --ip=$HOST --port=$PORT --env=dev
Run Code Online (Sandbox Code Playgroud)

产量

{ 
  l: true,
  H: true,
  R: true,
  s: true,
  ip: '127.0.0.1',
  port: '8080',
  env: 'dev'
}
Run Code Online (Sandbox Code Playgroud)


Llo*_*oyd 27

命令行args值得一看!

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

$ 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
Run Code Online (Sandbox Code Playgroud)

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

const optionDefinitions = [
  { name: 'verbose', alias: 'v', type: Boolean },
  { name: 'src', type: String, multiple: true, defaultOption: true },
  { name: 'timeout', alias: 't', type: Number }
]
Run Code Online (Sandbox Code Playgroud)

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

const commandLineArgs = require('command-line-args')
const options = commandLineArgs(optionDefinitions)
Run Code Online (Sandbox Code Playgroud)

options 现在看起来像这样:

{
  src: [
    'one.js',
    'two.js'
  ],
  verbose: true,
  timeout: 1000
}
Run Code Online (Sandbox Code Playgroud)

高级用法

除了上面的典型用法,您还可以配置命令行参数以接受更高级的语法表单.

表单中基于命令的语法(git样式):

$ executable <command> [options]
Run Code Online (Sandbox Code Playgroud)

例如.

$ git commit --squash -m "This is my commit message"
Run Code Online (Sandbox Code Playgroud)

表单中的命令和子命令语法(docker style):

$ executable <command> [options] <sub-command> [options]
Run Code Online (Sandbox Code Playgroud)

例如.

$ docker run --detached --image centos bash -c yum install -y httpd
Run Code Online (Sandbox Code Playgroud)

使用指南生成

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

典型的使用指南示例.

用法

所述聚合物-CLI使用指南是一个很好的真实的例子.

用法

进一步阅读

还有很多东西需要学习,请参阅维基以获取示例和文档.


Zla*_*tko 22

有一个应用程序.好吧,模块.好吧,不止一个,可能是几百个.

Yargs是一个有趣的人,它的文档很酷.

这是github/npm页面的一个例子:

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

输出在这里(它用破折号等读取选项,短和长,数字等).

$ ./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' ]
Run Code Online (Sandbox Code Playgroud)


小智 18

这是我的命名参数的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)
Run Code Online (Sandbox Code Playgroud)

例:

$ node test.js foo=bar fizz=buzz
bar
buzz
Run Code Online (Sandbox Code Playgroud)

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


Man*_*vel 18

基于标准输入解析参数 ( --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;
})();
Run Code Online (Sandbox Code Playgroud)

命令示例

node app.js --name=stackoverflow --id=10 another-argument --text="Hello World"
Run Code Online (Sandbox Code Playgroud)

argv 的结果: console.log(argv)

{
    name: "stackoverflow",
    id: "10",
    text: "Hello World"
}
Run Code Online (Sandbox Code Playgroud)

  • 这也让我感到惊讶。在我看来,这是最好的解决方案。我在我的项目中多次使用它。 (3认同)

小智 16

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

const {argv} = require('process')
Run Code Online (Sandbox Code Playgroud)

使用他们的参数运行程序。

$ node process-args.js one two=three four
Run Code Online (Sandbox Code Playgroud)

argv 是以下数组:

argv[0] = /usr/bin/node
argv[1] = /home/user/process-args.js
argv[2] = one
argv[3] = two=three
argv[4] = four
Run Code Online (Sandbox Code Playgroud)


mbe*_*sky 15

原生实验方法

Nodejs团队util.parseArgs在18.3.0和16.17.0版本中添加了功能。因此,如果您使用这些或更高版本的 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);
Run Code Online (Sandbox Code Playgroud)

输出样本:

$ 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'
]
Run Code Online (Sandbox Code Playgroud)


250*_*50R 11

使用nconf https://github.com/flatiron/nconf等集中管理配置可能是个好主意.

它可以帮助您使用配置文件,环境变量,命令行参数.


Jos*_*nac 11

没有图书馆:使用Array.prototype.reduce()

const args = process.argv.slice(2).reduce((acc, arg) => {

    let [k, v = true] = arg.split('=')
    acc[k] = v
    return acc

}, {})
Run Code Online (Sandbox Code Playgroud)

这个命令 node index.js count=2 print debug=false msg=hi

console.log(args) // { count: '2', print: true, debug: 'false', msg: 'hi' }
Run Code Online (Sandbox Code Playgroud)

也,

我们可以改变

    let [k, v = true] = arg.split('=')
    acc[k] = v
Run Code Online (Sandbox Code Playgroud)

通过(更长)

    let [k, v] = arg.split('=')
    acc[k] = v === undefined ? true : /true|false/.test(v) ? v === 'true' : /[\d|\.]+/.test(v) ? Number(v) : v
Run Code Online (Sandbox Code Playgroud)

自动解析布尔值和数字

console.log(args) // { count: 2, print: true, debug: false, msg: 'hi' }
Run Code Online (Sandbox Code Playgroud)


Piy*_*gar 10

传递,解析参数是一个简单的过程.Node为您提供process.argv属性,该属性是一个字符串数组,它是调用Node时使用的参数.数组的第一个条目是Node可执行文件,第二个条目是脚本的名称.

如果您使用以下参数运行脚本

$ node args.js arg1 arg2
Run Code Online (Sandbox Code Playgroud)

文件:args.js

console.log(process.argv)
Run Code Online (Sandbox Code Playgroud)

你会得到类似的数组

 ['node','args.js','arg1','arg2']
Run Code Online (Sandbox Code Playgroud)


Abd*_*UMI 9

npm install ps-grab
Run Code Online (Sandbox Code Playgroud)

如果你想运行这样的东西:

node greeting.js --user Abdennour --website http://abdennoor.com 
Run Code Online (Sandbox Code Playgroud)

-

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

或类似的东西:

node vbox.js -OS redhat -VM template-12332 ;
Run Code Online (Sandbox Code Playgroud)

-

var grab=require('ps-grab');
grab('-OS') // return 'redhat'
grab('-VM') // return 'template-12332'
Run Code Online (Sandbox Code Playgroud)

  • 这个 repo 在 github 上不再可用。 (2认同)

Nou*_*had 8

proj.js

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

终奌站:

nodemon app.js "arg1" "arg2" "arg3"
Run Code Online (Sandbox Code Playgroud)

结果:

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.
Run Code Online (Sandbox Code Playgroud)

阐释:

0 :您的机器中的node.exe目录(C:\ Program Files \nodejs \node.exe')

1:项目文件的目录.(proj.js)

2 :你的第一个节点参数(arg1)

3 :你的节点的第二个参数(arg2)

4 :节点的第三个参数(arg3)

你的实际参数从数组的2nd索引开始argv,即process.argv[2].


Joh*_*Lee 8

如果使用简单的参数(没有键+值),则使用Set解决位置问题。

例如,两个命令将返回相同的结果:

node server.js detail json
node server.js json detail
Run Code Online (Sandbox Code Playgroud)
node server.js detail json
node server.js json detail
Run Code Online (Sandbox Code Playgroud)

然后就可以使用args.has('detail')orargs.has('json')而不用担心位置。


Evr*_*tar 7

您可以使用命令行参数system.args.我使用下面的解决方案将参数解析为一个对象,所以我可以通过名称得到我想要的那个.

var system = require('system');

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

现在你不需要知道参数的索引.用它就像args.whatever

注意:您应该使用命名参数file.js x=1 y=2来使用此解决方案.


isa*_*ale 7

传递参数很容易,接收它们只是读取 process.argv 数组 Node 基本上可以从任何地方访问的问题。但是您肯定希望将它们作为键/值对来读取,因此您需要编写一段脚本来解释它。

Joseph Merdrignac 发布了一篇使用 reduce 的漂亮文章,但它依赖于key=value语法而不是-k valueand --key value。为了使用第二个标准,我将它改写得更丑、更久,我将其作为答案发布,因为它不适合作为评论。但它确实完成了工作。

   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
   },{})
Run Code Online (Sandbox Code Playgroud)

使用此代码,命令node 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"
}
Run Code Online (Sandbox Code Playgroud)


Ama*_*Bah 6

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

file: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;
}
Run Code Online (Sandbox Code Playgroud)

不仅仅是:

var arguments = require('./parse-cli-arguments')(['foo', 'bar', 'xpto']);
Run Code Online (Sandbox Code Playgroud)


Rob*_*ina 6

没有库的 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);
Run Code Online (Sandbox Code Playgroud)

输入:ts-node index.js -p param --parameter parameter

输出:{ p: 'param ', parameter: 'parameter' }


Cas*_*idy 5

没有图书馆

如果您想在 vanilla JS/ES6 中执行此操作,您可以使用以下解决方案

仅适用于NodeJS > 6

const args = process.argv
  .slice(2)
  .map((val, i)=>{
    let object = {};
    let [regexForProp, regexForVal] = (() => [new RegExp('^(.+?)='), new RegExp('\=(.*)')] )();
    let [prop, value] = (() => [regexForProp.exec(val), regexForVal.exec(val)] )();
    if(!prop){
      object[val] = true;
      return object;
    } else {
      object[prop[1]] = value[1] ;
      return object
    }
  })
  .reduce((obj, item) => {
    let prop = Object.keys(item)[0];
    obj[prop] = item[prop];
    return obj;
  }, {});
Run Code Online (Sandbox Code Playgroud)

而这个命令

node index.js host=http://google.com port=8080 production
Run Code Online (Sandbox Code Playgroud)

将产生以下结果

console.log(args);//{ host:'http://google.com',port:'8080',production:true }
console.log(args.host);//http://google.com
console.log(args.port);//8080
console.log(args.production);//true
Run Code Online (Sandbox Code Playgroud)

ps 如果您找到更优雅的解决方案,请更正 map 和 reduce 函数中的代码,谢谢;)


小智 5

在 Node.js 中检索参数的最简单方法是通过 process.argv 数组。这是一个全局对象,您无需导入任何其他库即可使用它。您只需将参数传递给 Node.js 应用程序,就像我们之前展示的那样,并且可以通过 process.argv 数组在应用程序中访问这些参数。

process.argv 数组的第一个元素始终是指向节点可执行文件的文件系统路径。第二个元素是正在执行的 JavaScript 文件的名称。第三个元素是用户实际传递的第一个参数。

'use strict';

for (let j = 0; j < process.argv.length; j++) {  
    console.log(j + ' -> ' + (process.argv[j]));
}
Run Code Online (Sandbox Code Playgroud)

该脚本所做的只是循环遍历 process.argv 数组并打印索引以及存储在这些索引中的元素。如果您对收到的参数以及参数的顺序有疑问,这对于调试非常有用。

您还可以使用 yargs 等库来处理 commnadline 参数。


Aks*_*put 5

虽然上面的答案很完美,而且有人已经建议了 yargs,但使用这个包真的很容易。这是一个很好的包,它使向命令行传递参数变得非常容易。

npm i yargs
const yargs = require("yargs");
const argv = yargs.argv;
console.log(argv);
Run Code Online (Sandbox Code Playgroud)

请访问https://yargs.js.org/了解更多信息。