简体   繁体   English

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

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

I have a web server written in Node.js and I would like to launch with a specific folder.我有一个用 Node.js 编写的web服务器,我想用一个特定的文件夹启动。 I'm not sure how to access arguments in JavaScript. I'm running node like this:我不确定如何访问 JavaScript 中的 arguments。我正在这样运行节点:

$ node server.js folder

here server.js is my server code.这里server.js是我的服务器代码。 Node.js help says this is possible: Node.js 帮助说这是可能的:

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

How would I access those arguments in JavaScript?我将如何访问 JavaScript 中的那些 arguments? Somehow I was not able to find this information on the web.不知何故,我无法在 web 上找到此信息。

Standard Method (no library)标准方法(无库)

The arguments are stored in process.argv参数存储在process.argv

Here are the node docs on handling command line args:以下是有关处理命令行参数的节点文档:

process.argv is an array containing the command line arguments. process.argv是一个包含命令行参数的数组。 The first element will be 'node', the second element will be the name of the JavaScript file.第一个元素将是“节点”,第二个元素将是 JavaScript 文件的名称。 The next elements will be any additional command line arguments.下一个元素将是任何其他命令行参数。

// 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

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 是您正在执行的脚本的位置。

The up-to-date right answer for this it to use the minimist library.最新的正确答案是使用minimist库。 We used to use node-optimist but it has since been deprecated.我们曾经使用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' }

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 :具有参数解析的成熟/交互式命令行应用程序。

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 yargs which is an active fork of optimist.试试yargs ,它是乐观主义者的活跃分支。

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.这与 bash 脚本访问参数值的方式非常相似,并且正如 MooGoo 指出的那样,它已经为 node.js 提供了标准。 (Just to make it understandable to somebody that's new to 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"

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.如果您喜欢生成器方法,那么非常适合从用户那里获取输入。

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

Stdio Library标准库

The easiest way to parse command-line arguments in NodeJS is using the stdio module.在 NodeJS 中解析命令行参数的最简单方法是使用stdio模块。 Inspired by UNIX getopt utility, it is as trivial as follows:受 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'}
});

If you run the previous code with this command:如果您使用此命令运行前面的代码:

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

Then ops object 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 -om instead of -o -m .还支持分组选项,因此您可以编写-om而不是-o -m

Furthermore, stdio can generate a help/usage output automatically.此外, stdio可以自动生成帮助/使用输出。 If you call ops.printHelp() you'll get the following:如果你调用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 stdio module using NPM :您可以使用NPM安装stdio模块:

npm install stdio

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'

command-line-args is worth a look!命令行参数值得一看!

You can set options using the main notation standards ( learn more ).您可以使用主要符号标准设置选项( 了解更多)。 These commands are all equivalent, setting the same values:这些命令都是等效的,设置相同的值:

$ 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

To access the values, first create a list of option definitions describing the options your application accepts.要访问这些值,首先创建一个选项定义列表,描述您的应用程序接受的选项。 The type property is a setter function (the value supplied is passed through this), giving you full control over the value received. type属性是一个 setter 函数(提供的值通过 this 传递),使您可以完全控制接收到的值。

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

Next, parse the options using commandLineArgs() :接下来,使用commandLineArgs()解析选项:

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

options now looks like this: options现在看起来像这样:

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

Advanced usage高级用法

Beside the above typical usage, you can configure command-line-args to accept more advanced syntax forms.除了上述典型用法,您还可以配置 command-line-args 以接受更高级的语法形式。

Command-based syntax (git style) in the form: 形式为基于命令的语法(git 风格):

$ executable <command> [options]

For example.例如。

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

Command and sub-command syntax (docker style) in the form: 形式的命令和子命令语法(docker 风格):

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

For example.例如。

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

Usage guide generation使用指南生成

A usage guide (typically printed when --help is set) can be generated using command-line-usage .可以使用command-line-usage生成使用指南(通常在设置--help时打印)。 See the examples below and read the documentation for instructions how to create them.请参阅下面的示例并阅读文档以了解如何创建它们。

A typical usage guide example.一个典型的使用指南示例。

用法

The polymer-cli usage guide is a good real-life example.聚合物 cli使用指南是一个很好的现实例子。

用法

Further Reading进一步阅读

There is plenty more to learn, please see the wiki for examples and documentation.还有很多东西要学习,请参阅wiki以获取示例和文档。

Here's my 0-dep solution for named arguments:这是我的命名参数的 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)

Example:例子:

$ node test.js foo=bar fizz=buzz
bar
buzz

Note: Naturally this will fail when the argument contains a = .注意:当参数包含=时,这自然会失败。 This is only for very simple usage.这仅用于非常简单的用法。

There's an app for that.有一个应用程序。 Well, module.嗯,模块。 Well, more than one, probably hundreds.嗯,不止一个,可能是数百个。

Yargs is one of the fun ones, its docs are cool to read. Yargs是其中之一,它的文档读起来很酷。

Here's an example from the github/npm page:这是来自 github/npm 页面的示例:

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

Output is here (it reads options with dashes etc, short and long, numeric etc).输出在这里(它读取带有破折号等,短和长,数字等的选项)。

$ ./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' ]

Parsing argument based on standard input ( --key=value )基于标准输入解析参数( --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;
})();

Command example命令示例

node app.js --name=stackoverflow --id=10 another-argument --text="Hello World"

Result of argv: console.log(argv) argv 的结果: console.log(argv)

{
    name: "stackoverflow",
    id: "10",
    text: "Hello World"
}

proj.js项目.js

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

Terminal:终端:

nodemon app.js "arg1" "arg2" "arg3"

Result:结果:

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.

Explaination:说明:

  1. The directory of node.exe in your machine ( C:\\Program Files\\nodejs\\node.exe )您机器中 node.exe 的目录( C:\\Program Files\\nodejs\\node.exe
  2. The directory of your project file ( proj.js )项目文件的目录 ( proj.js )
  3. Your first argument to node ( arg1 )您对节点( arg1 )的第一个参数
  4. Your second argument to node ( arg2 )您对节点( arg2 )的第二个参数
  5. Your third argument to node ( arg3 )您对节点的第三个参数( arg3

your actual arguments start form second index of argv array, that is process.argv[2] .您的实际参数从argv数组的第二个索引开始,即process.argv[2]

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

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

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

}, {})

for this command node index.js count=2 print debug=false msg=hi对于此命令node index.js count=2 print debug=false msg=hi

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

also,还,

we can change我们可以改变

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

by (much longer)通过(更长的时间)

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

to auto parse Boolean & Number自动解析布尔值和数字

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

Passing,parsing arguments is an easy process.传递、解析参数是一个简单的过程。 Node provides you with the process.argv property, which is an array of strings, which are the arguments that were used when Node was invoked. Node 为您提供 process.argv 属性,它是一个字符串数组,是调用 Node 时使用的参数。 The first entry of the array is the Node executable, and the second entry is the name of your script.数组的第一个条目是 Node 可执行文件,第二个条目是脚本的名称。

If you run script with below atguments如果您使用以下参数运行脚本

$ node args.js arg1 arg2

File : args.js文件:args.js

console.log(process.argv)

You will get array like你会得到像

 ['node','args.js','arg1','arg2']

It's probably a good idea to manage your configuration in a centralized manner using something like nconf https://github.com/flatiron/nconf 使用nconf https://github.com/flatiron/nconf之类的集中方式来管理您的配置可能是一个好主意

It helps you work with configuration files, environment variables, command-line arguments. 它可以帮助您使用配置文件,环境变量,命令行参数。

In the node code require the built in process lib.在节点代码中需要内置的进程库。

const {argv} = require('process')

Run the program with their arguments.使用他们的 arguments 运行程序。

$ node process-args.js one two=three four

argv is the array that follows: argv 是后面的数组:

argv[0] = /usr/bin/node
argv[1] = /home/user/process-args.js
argv[2] = one
argv[3] = two=three
argv[4] = four
npm install ps-grab

If you want to run something like this :如果你想运行这样的东西:

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

-- ——

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

Or something like :或类似的东西:

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

-- ——

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

You can reach command line arguments using system.args .您可以使用system.args访问命令行参数。 And i use the solution below to parse arguments into an object, so i can get which one i want by name.我使用下面的解决方案将参数解析为一个对象,这样我就可以通过名称获得我想要的那个。

var system = require('system');

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

now you don't need to know the index of the argument.现在您不需要知道参数的索引。 use it like args.whateverargs.whatever一样使用它

Note: you should use named arguments like file.js x=1 y=2 to use this solution.注意:你应该使用像file.js x=1 y=2这样的命名参数来使用这个解决方案。

You can parse all arguments and check if they exist.您可以解析所有参数并检查它们是否存在。

file: parse-cli-arguments.js:文件:解析-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;
}

Than just do:不仅仅是做:

var arguments = require('./parse-cli-arguments')(['foo', 'bar', 'xpto']);

Passing arguments is easy, and receiving them is just a matter of reading the process.argv array Node makes accessible from everywhere, basically.传递参数很容易,接收它们只是读取 process.argv 数组 Node 基本上可以从任何地方访问的问题。 But you're sure to want to read them as key/value pairs, so you'll need a piece to script to interpret it.但是您肯定希望将它们作为键/值对来读取,因此您需要编写一段脚本来解释它。

Joseph Merdrignac posted a beautiful one using reduce, but it relied on a key=value syntax instead of -k value and --key value . Joseph Merdrignac 发布了一个使用 reduce 的漂亮的,但它依赖于key=value语法而不是-k value--key value I rewrote it much uglier and longer to use that second standard, and I'll post it as an answer because it wouldn't fit as a commentary.为了使用第二个标准,我将它改写得更丑、更久,我将其作为答案发布,因为它不适合作为评论。 But it does get the job done.但它确实完成了工作。

   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
   },{})

With this code a command node script.js alpha beta -charlie delta --echo foxtrot would give you the following object使用此代码,命令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"
}

Without libraries没有图书馆

If you want to do this in vanilla JS/ES6 you can use the following solution如果您想在 vanilla JS/ES6 中执行此操作,您可以使用以下解决方案

worked only in NodeJS > 6仅适用于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;
  }, {});

And this command而这个命令

node index.js host=http://google.com port=8080 production

will produce the following result将产生以下结果

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

ps Please correct the code in map and reduce function if you find more elegant solution, thanks ;) ps 如果您找到更优雅的解决方案,请更正 map 和 reduce 函数中的代码,谢谢;)

Although Above answers are perfect, and someone has already suggested yargs, using the package is really easy.虽然上面的答案很完美,而且有人已经建议了 yargs,但使用这个包真的很容易。 This is a nice package which makes passing arguments to command line really easy.这是一个很好的包,它使向命令行传递参数变得非常容易。

npm i yargs
const yargs = require("yargs");
const argv = yargs.argv;
console.log(argv);

Please visit https://yargs.js.org/ for more info.请访问https://yargs.js.org/了解更多信息。

TypeScript solution with no libraries:没有库的 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);

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

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

The simplest way of retrieving arguments in Node.js is via the process.argv array.在 Node.js 中检索参数的最简单方法是通过 process.argv 数组。 This is a global object that you can use without importing any additional libraries to use it.这是一个全局对象,您无需导入任何其他库即可使用它。 You simply need to pass arguments to a Node.js application, just like we showed earlier, and these arguments can be accessed within the application via the process.argv array.您只需要将参数传递给 Node.js 应用程序,就像我们之前展示的那样,并且可以通过 process.argv 数组在应用程序中访问这些参数。

The first element of the process.argv array will always be a file system path pointing to the node executable. process.argv 数组的第一个元素将始终是指向节点可执行文件的文件系统路径。 The second element is the name of the JavaScript file that is being executed.第二个元素是正在执行的 JavaScript 文件的名称。 And the third element is the first argument that was actually passed by the user.第三个元素是用户实际传递的第一个参数。

'use strict';

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

All this script does is loop through the process.argv array and prints the indexes, along with the elements stored in those indexes.这个脚本所做的就是遍历 process.argv 数组并打印索引以及存储在这些索引中的元素。 It's very useful for debugging if you ever question what arguments you're receiving, and in what order.如果您质疑您收到的参数以及顺序,这对于调试非常有用。

You can also use libraries like yargs for working with commnadline arguments.您还可以使用像 yargs 这样的库来处理 commnadline 参数。

Simple + ES6 + no-dependency + supports boolean flags简单 + 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 }=` , '' );
}

Output:输出:

  • If invoked with node app.js then argv('foo') will return null如果使用node app.js调用,则argv('foo')将返回null
  • If invoked with node app.js --foo then argv('foo') will return true如果使用node app.js --foo调用,则argv('foo')将返回true
  • If invoked with node app.js --foo= then argv('foo') will return ''如果使用node app.js --foo=调用,则argv('foo')将返回''
  • If invoked with node app.js --foo=bar then argv('foo') will return 'bar'如果使用node app.js --foo=bar调用,则argv('foo')将返回'bar'

NodeJS exposes a global variable called process . NodeJS 公开了一个名为process的全局变量。

we can use:我们可以用:

process.argv

to get the command line arguments passes to our script.获取命令行 arguments 传递给我们的脚本。

The output of process.argv will be a list in the following order: process.argv的 output 将是一个按以下顺序排列的列表:

[
full-path-to-node-executable,
full-path-to-the-script-file
...additonal-arguments-we-provide
]

process.argv is your friend, capturing command line args is natively supported in Node JS. process.argv是您的朋友,Node JS 本身支持捕获命令行参数。 See example below::请参阅下面的示例::

process.argv.forEach((val, index) => {
  console.log(`${index}: ${val}`);
})

ES6-style no-dependencies solution: ES6 风格的无依赖解决方案:

const longArgs = arg => {
    const [ key, value ] = arg.split('=');
    return { [key.slice(2)]: value || true }
};

const flags = arg => [...arg.slice(1)].reduce((flagObj, f) => ({ ...flagObj, [f]: true }), {});


const args = () =>
    process.argv
        .slice(2)
        .reduce((args, arg) => ({
            ...args,
            ...((arg.startsWith('--') && longArgs(arg)) || (arg[0] === '-' && flags(arg)))
        }), {});

console.log(args());

Use the minimist npm package. it is the easiest method and don't need to worry about anything.使用最简单的 npm package。这是最简单的方法,不需要担心任何事情。

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

We can use it in windows task scheduler too.我们也可以在 windows 任务调度程序中使用它。

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

I extended the getArgs function just to get also commands, as well as flags ( -f , --anotherflag ) and named args ( --data=blablabla ):我扩展了getArgs函数只是为了获取命令,以及标志( -f--anotherflag )和命名参数( --data=blablabla ):

  1. The module模块
/**
 * @module getArgs.js
 * get command line arguments (commands, named arguments, flags)
 *
 * @see https://stackoverflow.com/a/54098693/1786393
 *
 * @return {Object}
 *
 */
function getArgs () {
  const commands = []
  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
        })
      }
     else {
      // commands
      commands.push(arg)
     } 
    })
  return { args, commands }
}


// test
if (require.main === module) {
  // node getArgs test --dir=examples/getUserName --start=getUserName.askName
  console.log( getArgs() )
}

module.exports = { getArgs }

  1. Usage example:用法示例:
$ node lib/getArgs test --dir=examples/getUserName --start=getUserName.askName
{
  args: { dir: 'examples/getUserName', start: 'getUserName.askName' },
  commands: [ 'test' ]
}

$ node lib/getArgs --dir=examples/getUserName --start=getUserName.askName test tutorial
{
  args: { dir: 'examples/getUserName', start: 'getUserName.askName' },
  commands: [ 'test', 'tutorial' ]
}

You can get command-line information from process.argv()您可以从process.argv()获取命令行信息

And I don't want to limit the problem to node.js .而且我不想将问题限制在node.js Instead, I want to turn it into how to parse the string as the argument.相反,我想把它变成如何将字符串解析为参数。

console.log(ArgumentParser(`--debug --msg="Hello World" --title="Test" --desc=demo -open --level=5 --MyFloat=3.14`))

output输出

{
  "debug": true,
  "msg": "Hello World",
  "title": "Test",
  "desc": "demo",
  "open": true,
  "level": 5,
  "MyFloat": 3.14
}

code代码

Pure javascript, no dependencies needed纯javascript,不需要依赖

 // 👇 Below is Test (() => { window.onload = () => { const testArray = [ `--debug --msg="Hello World" --title="Test" --desc=demo -open --level=5 --MyFloat=3.14`, ] for (const testData of testArray) { try { const obj = ArgumentParser(testData) console.log(obj) } catch (e) { console.error(e.message) } } } })() // 👇 Script class ParserError extends Error { } function Cursor(str, pos) { this.str = str this.pos = pos this.MoveRight = (step = 1) => { this.pos += step } this.MoveToNextPara = () => { const curStr = this.str.substring(this.pos) const match = /^(?<all> *--?(?<name>[a-zA-Z_][a-zA-Z0-9_]*)(=(?<value>[^-]*))?)/g.exec(curStr) // https://regex101.com/r/k004Gv/2 if (match) { let {groups: {all, name, value}} = match if (value !== undefined) { value = value.trim() if (value.slice(0, 1) === '"') { // string if (value.slice(-1) !== '"') { throw new ParserError(`Parsing error: '"' expected`) } value = value.slice(1, -1) } else { // number or string (without '"') value = isNaN(Number(value)) ? String(value) : Number(value) } } this.MoveRight(all.length) return [name, value ?? true] // If the value is undefined, then set it as ture. } throw new ParserError(`illegal format detected. ${curStr}`) } } function ArgumentParser(str) { const obj = {} const cursor = new Cursor(str, 0) while (1) { const [name, value] = cursor.MoveToNextPara() obj[name] = value if (cursor.pos === str.length) { return obj } } }

Native Experimental Method本地实验方法

Nodejs team added util.parseArgs function in versions 18.3.0 and 16.17.0. Nodejs 团队在版本 18.3.0 和 16.17.0 中添加了util.parseArgs function。 So if you use these or higher versions of nodejs you can parse command line arguments with this native solution.因此,如果您使用这些或更高版本的 nodejs,则可以使用此本机解决方案解析命令行 arguments。

An example of usage from the documentation:文档中的用法示例:

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

Output sample: Output 样本:

$ 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'
]

as stated in the node docs The process.argv property returns an array containing the command line arguments passed when the Node.js process was launched.如节点文档中所述 process.argv 属性返回一个数组,其中包含启动 Node.js 进程时传递的命令行参数。

For example, assuming the following script for process-args.js:例如,假设 process-args.js 有以下脚本:

// print process.argv
process.argv.forEach((val, index) => {
   console.log(`${index}: ${val}`);
});

Launching the Node.js process as:以如下方式启动 Node.js 进程:

 $ node process-args.js one two=three four

Would generate the output:将生成输出:

0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four

Most of the people have given good answers.大多数人都给出了很好的答案。 I would also like to contribute something here.我也想在这里贡献一些东西。 I am providing the answer using lodash library to iterate through all command line arguments we pass while starting the app:我正在使用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();

To run above code just run following commands:要运行上面的代码,只需运行以下命令:

npm install
node index.js xyz abc 123 456

The result will be:结果将是:

xyz 
abc 
123
456

The best way to pass command line arguments to a Node.js program is by using a Command Line Interface (CLI) 将命令行参数传递给Node.js程序的最佳方法是使用命令行界面(CLI)

There is a nifty npm module called nodejs-cli that you can use. 您可以使用一个漂亮的npm模块,称为nodejs-cli

If you want to create one with no dependencies I've got one on my Github if you wanna check it out, it's actually quite simple and easy to use, click here . 如果您想创建一个没有依赖性的程序,我想在Github上创建一个程序,如果您想查看它,它实际上非常简单易用,请单击此处

If you want to use unix style flags like server -f fileURI then use the ray-fs library for NodeJS.如果你想使用像server -f fileURI这样的 unix 样式标志,那么使用server -f fileURIray-fs库。 Its very easy to use!它非常容易使用!

The original question was asking to pass command line arguments, not about more complex parsing of arguments.最初的问题是要求传递命令行参数,而不是更复杂的参数解析。 Yet with all the complex answers, they all missed one simple, useful variation.然而,对于所有复杂的答案,他们都错过了一个简单而有用的变化。

Did you know that the Unix shell supports named arguments?您知道 Unix shell 支持命名参数吗? This dates back to the original Bourne shell in the 1980s.这可以追溯到 1980 年代的原始 Bourne shell。 Usage is simple:用法很简单:

$ FOO=one BAR=two nodejs myscript.js

To fetch the parameters in Javascript:在 Javascript 中获取参数:

var foo = process.env.FOO;
var bar = process.env.BAR;

Named parameters are much easier to read, once you get past two or three parameters.一旦超过两个或三个参数,命名参数就更容易阅读。 Optional parameters are simple, and order is not fixed.可选参数简单,顺序不固定。

(This might even work on Windows, with the recent support for Unix shells.) (这甚至可能适用于 Windows,因为最近支持 Unix shell。)

Also, shockingly few Unix programmers know of this usage.此外,令人震惊的是,很少有 Unix 程序员知道这种用法。 :) :)

A simple snippet if any need it: 一个简单的片段,如果有的话需要它:

var fs = require('fs'), objMod = {};

process.argv.slice(2).map(function(y, i) {
  y = y.split('=');
  if (y[0] && y[1]) objMod[y[0]] = y[1];
  else console.log('Error in argument number ' + (i+1));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM