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

$ node server.js folder

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

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

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


当前回答

没有库

如果您想在vanilla JS/ES6中执行此操作,可以使用以下解决方案

仅在NodeJS>6中工作

const args = process.argv
  .slice(2)
  .map((val, i)=>{
    let object = {};
    let [regexForProp, regexForVal] = (() => [new RegExp('^(.+?)='), new RegExp('\=(.*)')] )();
    let [prop, value] = (() => [regexForProp.exec(val), regexForVal.exec(val)] )();
    if(!prop){
      object[val] = true;
      return object;
    } else {
      object[prop[1]] = value[1] ;
      return object
    }
  })
  .reduce((obj, item) => {
    let prop = Object.keys(item)[0];
    obj[prop] = item[prop];
    return obj;
  }, {});

这个命令

node index.js host=http://google.com port=8080 production

将产生以下结果

console.log(args);//{ host:'http://google.com',port:'8080',production:true }
console.log(args.host);//http://google.com
console.log(args.port);//8080
console.log(args.production);//true

p.s.请更正map和reduce函数中的代码如果您找到更优雅的解决方案,谢谢;)

其他回答

传递参数很简单,接收它们只需读取进程即可。argv array Node基本上可以从任何地方访问。但您肯定希望将它们作为键/值对来读取,因此需要编写一段脚本来解释它。

JosephMerdrignac使用reduce发布了一个漂亮的例子,但它依赖于key=value语法,而不是-kvalue和--keyvalue。我把它重写得更丑、更长,以使用第二种标准,我会把它作为答案发布,因为它不适合作为评论。但它确实完成了任务。

   const args = process.argv.slice(2).reduce((acc,arg,cur,arr)=>{
     if(arg.match(/^--/)){
       acc[arg.substring(2)] = true
       acc['_lastkey'] = arg.substring(2)
     } else
     if(arg.match(/^-[^-]/)){
       for(key of arg.substring(1).split('')){
         acc[key] = true
         acc['_lastkey'] = key
       }
     } else
       if(acc['_lastkey']){
         acc[acc['_lastkey']] = arg
         delete acc['_lastkey']
       } else
         acc[arg] = true
     if(cur==arr.length-1)
       delete acc['_lastkey']
     return acc
   },{})

使用此代码,命令节点script.js alpha beta-charlie delta--echo foxtrot将为您提供以下对象


args = {
 "alpha":true,
 "beta":true,
 "c":true,
 "h":true,
 "a":true,
 "r":true
 "l":true,
 "i":true,
 "e":"delta",
 "echo":"foxtrot"
}

以下是我的命名参数的0-dep解决方案:

const args = process.argv
    .slice(2)
    .map(arg => arg.split('='))
    .reduce((args, [value, key]) => {
        args[value] = key;
        return args;
    }, {});

console.log(args.foo)
console.log(args.fizz)

例子:

$ node test.js foo=bar fizz=buzz
bar
buzz

注意:当参数包含=时,这自然会失败。这仅用于非常简单的用途。

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

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

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

如节点文档中所述process.argv属性返回一个数组,其中包含Node.js进程启动时传递的命令行参数。

例如,假设process-args.js的脚本如下:

// print process.argv
process.argv.forEach((val, index) => {
   console.log(`${index}: ${val}`);
});

以如下方式启动Node.js进程:

 $ node process-args.js one two=three four

将生成输出:

0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four

您可以使用system.args获取命令行参数。我使用下面的解决方案将参数解析为一个对象,这样我就可以按名称获取所需的参数。

var system = require('system');

var args = {};
system.args.map(function(x){return x.split("=")})
    .map(function(y){args[y[0]]=y[1]});

现在你不需要知道参数的索引。像args.whatever一样使用它

注意:应该使用file.js x=1y=2这样的命名参数这一解决方案。