Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

javascript - 如何将命令行参数传递给Node.js程序?(How do I pass command line arguments to a Node.js program?)

I have a web server written in Node.js and I would like to launch with a specific folder.

(我有一个用Node.js编写的Web服务器,我想使用一个特定的文件夹启动。)

I'm not sure how to access arguments in JavaScript.

(我不确定如何在JavaScript中访问参数。)

I'm running node like this:

(我正在像这样运行节点:)

$ node server.js folder

here server.js is my server code.

(这是server.js是我的服务器代码。)

Node.js help says this is possible:

(Node.js帮助说这是可能的:)

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

How would I access those arguments in JavaScript?

(如何在JavaScript中访问这些参数?)

Somehow I was not able to find this information on the web.

(不知何故,我无法在网上找到此信息。)

  ask by milkplus translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Standard Method (no library)(标准方法(无库))

The arguments are stored in process.argv

(参数存储在process.argv)

Here are the node docs on handling command line args:

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

process.argv is an array containing the command line arguments.

(process.argv是一个包含命令行参数的数组。)

The first element will be 'node', the second element will be the name of the JavaScript file.

(第一个元素是'node',第二个元素是JavaScript文件的名称。)

The next elements will be any additional command line arguments.

(接下来的元素将是任何其他命令行参数。)

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

This will generate:

(这将生成:)

$ 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...