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

$ node server.js folder

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

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

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


当前回答

为了像常规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'

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'

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

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

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

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