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

$ node server.js folder

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

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

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


当前回答

命令行参数值得一看!

您可以使用主要符号标准设置选项(了解更多信息)。这些命令都是等效的,设置相同的值:

$ example --verbose --timeout=1000 --src one.js --src two.js
$ example --verbose --timeout 1000 --src one.js two.js
$ example -vt 1000 --src one.js two.js
$ example -vt 1000 one.js two.js

要访问这些值,首先创建一个选项定义列表,描述应用程序接受的选项。type属性是setter函数(提供的值通过该函数传递),使您能够完全控制接收的值。

const optionDefinitions = [
  { name: 'verbose', alias: 'v', type: Boolean },
  { name: 'src', type: String, multiple: true, defaultOption: true },
  { name: 'timeout', alias: 't', type: Number }
]

接下来,使用commandLineArgs()解析选项:

const commandLineArgs = require('command-line-args')
const options = commandLineArgs(optionDefinitions)

选项现在看起来如下:

{
  src: [
    'one.js',
    'two.js'
  ],
  verbose: true,
  timeout: 1000
}

高级用法

除了上述典型用法外,还可以配置命令行参数以接受更高级的语法形式。

基于命令的语法(git样式),格式为:

$ executable <command> [options]

例如

$ git commit --squash -m "This is my commit message"

命令和子命令语法(docker样式),格式如下:

$ executable <command> [options] <sub-command> [options]

例如

$ docker run --detached --image centos bash -c yum install -y httpd

生成使用指南

可以使用命令行用法生成使用指南(通常在设置--help时打印)。请参阅下面的示例并阅读文档以了解如何创建它们。

典型的使用指南示例。

聚合物cli使用指南是一个很好的现实例子。

进一步阅读

还有很多需要学习的内容,请参见wiki获取示例和文档。

其他回答

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

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

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

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

项目.js

for(var i=0;i<process.argv.length;i++){
  console.log(process.argv[i]);
}

终端:

nodemon app.js "arg1" "arg2" "arg3"

结果:

0 'C:\\Program Files\\nodejs\\node.exe'
1 'C:\\Users\\Nouman\\Desktop\\Node\\camer nodejs\\proj.js'
2 'arg1' your first argument you passed.
3 'arg2' your second argument you passed.
4 'arg3' your third argument you passed.

解释:

计算机中node.exe的目录(C:\Program Files\nodejs\node.exe)项目文件的目录(项目js)节点(arg1)的第一个参数节点的第二个参数(arg2)节点的第三个参数(arg3)


实际参数从argv数组的第二个索引开始,即process.argv[2]。

没有库

如果您想在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"
}