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

$ node server.js folder

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

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

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


当前回答

基于标准输入分析参数(--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;
})();

命令示例

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

argv的结果:console.log(argv)

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

其他回答

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


Vanilla javascript参数解析:

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

这将返回:

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

官方文件


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

Minimist:用于最小参数解析。

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

喵:Commander.js的更轻替代品

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

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

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

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

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

最初的问题是要求传递命令行参数,而不是更复杂的参数解析。然而,面对所有复杂的答案,他们都错过了一个简单而有用的变化。

你知道Unix shell支持命名参数吗?这可以追溯到20世纪80年代最初的伯恩贝壳。用法很简单:

$ FOO=one BAR=two nodejs myscript.js

要获取Javascript中的参数:

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

一旦超过两个或三个参数,命名参数就更容易读取。可选参数很简单,顺序也不固定。

(这甚至可以在Windows上运行,因为最近支持Unix shell。)

而且,几乎没有Unix程序员知道这种用法

最新的正确答案是使用最小化库。我们曾经使用节点乐观主义,但现在已经被弃用了。

下面是一个如何直接从最小化文档中使用它的示例:

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

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'