如何将命令行参数传递给 Node.js 程序? [英] How do I pass command line arguments to a Node.js program?

查看:33
本文介绍了如何将命令行参数传递给 Node.js 程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 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 是一个包含命令行参数的数组.第一个元素将是节点",第二个元素将是 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆