如何将命令行参数传递给Node.js程序? [英] How do I pass command line arguments to a Node.js program?
问题描述
我有一个用 Node.js 编写的网络服务器,我想推出使用特定文件夹。我不确定如何在JavaScript中访问参数。我正在运行这样的节点:
I have a web server written in Node.js and I would like to launch with a specific folder. I'm not sure how to access arguments in JavaScript. I'm running node like this:
$ node server.js folder
此处 server.js
是我的服务器代码。 Node.js帮助说这是可能的:
here server.js
is my server code. Node.js help says this is possible:
$ node -h
Usage: node [options] script.js [arguments]
我如何在JavaScript中访问这些参数?不知怎的,我无法在网上找到这些信息。
How would I access those arguments in JavaScript? Somehow I was not able to find this information on the web.
推荐答案
标准方法(无库)
参数存储在 process.argv
process.argv
是一个包含命令行参数的数组。第一个元素是'node',第二个元素是JavaScript文件的名称。下一个元素将是任何其他命令行参数。
process.argv
is an array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.
// 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
这篇关于如何将命令行参数传递给Node.js程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!