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

$ node server.js folder

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

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

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


当前回答

Simple+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 }=` , '' );
}

输出:

如果使用节点app.js调用,则argv('fo')将返回null如果使用节点app.js--foo调用,则argv('fo')将返回true如果使用节点app.js调用--foo=,则argv('fo')将返回“”如果使用节点app.js--foo=bar调用,则argv('fo')将返回'bar'

其他回答

我扩展了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' ]
}

npm install ps-grab

如果您想运行以下内容:

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

--

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

或者类似于:

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

--

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

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

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

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

$ node args.js arg1 arg2

文件:args.js

console.log(process.argv)

您将获得类似数组的

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

Simple+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 }=` , '' );
}

输出:

如果使用节点app.js调用,则argv('fo')将返回null如果使用节点app.js--foo调用,则argv('fo')将返回true如果使用节点app.js调用--foo=,则argv('fo')将返回“”如果使用节点app.js--foo=bar调用,则argv('fo')将返回'bar'