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

$ node server.js folder

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

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

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


当前回答

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'

其他回答

项目.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]。

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

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

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

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

标准方法(无库)

参数存储在process.argv中

以下是关于处理命令行参数的节点文档:

process.argv是一个包含命令行参数的数组。第一个元素是“node”,第二个元素是JavaScript文件的名称。接下来的元素将是任何其他命令行参数。

// print process.argv
process.argv.forEach(function (val, index, array) {
  console.log(index + ': ' + val);
});

这将产生:

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

process.argv是您的朋友,在NodeJS中本机支持捕获命令行参数。参见以下示例:

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