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

$ node server.js folder

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

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

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


当前回答

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

其他回答

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

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

使现代化

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

whithout libraries:使用Array.protocol.reduce()

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

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

}, {})

对于此命令节点,index.js count=2 print debug=false msg=hi

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

而且

我们可以改变

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

由(更长)

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

自动分析布尔数字(&N)

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

一个简单的片段(如果需要):

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

为了像常规javascript函数那样规范化参数,我在node.js shell脚本中执行以下操作:

var args = process.argv.slice(2);

注意,第一个参数通常是nodejs的路径,第二个参数是您正在执行的脚本的位置。

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'