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

$ node server.js folder

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

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

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


当前回答

以下是我的命名参数的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

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

其他回答

没有库的TypeScript解决方案:

interface IParams {
  [key: string]: string
}

function parseCliParams(): IParams {
  const args: IParams = {};
  const rawArgs = process.argv.slice(2, process.argv.length);
  rawArgs.forEach((arg: string, index) => {
    // Long arguments with '--' flags:
    if (arg.slice(0, 2).includes('--')) {
      const longArgKey = arg.slice(2, arg.length);
      const longArgValue = rawArgs[index + 1]; // Next value, e.g.: --connection connection_name
      args[longArgKey] = longArgValue;
    }
    // Shot arguments with '-' flags:
    else if (arg.slice(0, 1).includes('-')) {
      const longArgKey = arg.slice(1, arg.length);
      const longArgValue = rawArgs[index + 1]; // Next value, e.g.: -c connection_name
      args[longArgKey] = longArgValue;
    }
  });
  return args;
}

const params = parseCliParams();
console.log('params: ', params);

输入:ts node index.js-p param--参数参数

输出:{p:“param”,参数:“parameter”}

您可以使用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这样的命名参数这一解决方案。

传递、解析参数是一个简单的过程。Node为您提供process.argv属性,它是字符串数组,是调用Node时使用的参数。数组的第一个条目是Node可执行文件,第二个条目是脚本的名称。

如果您使用以下参数运行脚本

$ node args.js arg1 arg2

文件:args.js

console.log(process.argv)

您将获得类似数组的

 ['node','args.js','arg1','arg2']

以下是我的命名参数的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

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

在节点代码中需要内置的进程库。

const {argv} = require('process')

用它们的参数运行程序。

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

argv是以下数组:

argv[0] = /usr/bin/node
argv[1] = /home/user/process-args.js
argv[2] = one
argv[3] = two=three
argv[4] = four