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

$ node server.js folder

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

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

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


当前回答

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

查看乐观主义库,它比手动解析命令行选项要好得多。

使现代化

Optimist已弃用。试试雅格士,它是乐观主义者的积极分支。

其他回答

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

我扩展了getArgs函数,只获取命令,以及标志(-f,--anotherflag)和命名的args(--data=blablabla):

模块

/**
 * @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 }

用法示例:

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

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

有一个应用程序可以解决这个问题。嗯,模块。嗯,不止一个,可能有几百个。

Yargs是其中一个有趣的,它的文档很好读。

下面是github/npm页面的一个示例:

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

输出在这里(它读取带有破折号等的选项,短和长,数字等)。

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

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

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

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