mil*_*lus 2280 javascript arguments command-line-arguments node.js
我有一个用Node.js编写的Web服务器,我想用特定的文件夹启动.我不确定如何在JavaScript中访问参数.我正在运行这样的节点:
$ node server.js folder
Run Code Online (Sandbox Code Playgroud)
这server.js是我的服务器代码.Node.js帮助说这是可能的:
$ node -h
Usage: node [options] script.js [arguments]
Run Code Online (Sandbox Code Playgroud)
我如何在JavaScript中访问这些参数?不知怎的,我无法在网上找到这些信息.
Moo*_*Goo 2914
参数存储在 process.argv
process.argv是包含命令行参数的数组.第一个元素是'node',第二个元素是JavaScript文件的名称.下一个元素将是任何其他命令行参数.
// print process.argv
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
});
Run Code Online (Sandbox Code Playgroud)
这将产生:
$ 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
Run Code Online (Sandbox Code Playgroud)
Mau*_*ord 636
要像普通的javascript函数那样规范化参数,我会在node.js shell脚本中执行此操作:
var args = process.argv.slice(2);
Run Code Online (Sandbox Code Playgroud)
请注意,第一个arg通常是nodejs的路径,第二个arg是您正在执行的脚本的位置.
rea*_*ate 332
最新的正确答案,它使用最小化库.我们曾经使用node-optimist但它已被弃用.
以下是直接从最小化文档中使用它的示例:
var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);
Run Code Online (Sandbox Code Playgroud)
-
$ node example/parse.js -a beep -b boop
{ _: [], a: 'beep', b: 'boop' }
Run Code Online (Sandbox Code Playgroud)
-
$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz
{ _: [ 'foo', 'bar', 'baz' ],
x: 3,
y: 4,
n: 5,
a: true,
b: true,
c: true,
beep: 'boop' }
Run Code Online (Sandbox Code Playgroud)
dth*_*ree 297
const args = process.argv;
console.log(args);
Run Code Online (Sandbox Code Playgroud)
返回:
$ node server.js one two=three four
['node', '/home/server.js', 'one', 'two=three', 'four']
Run Code Online (Sandbox Code Playgroud)
Minimist:用于最小化参数解析.
Commander.js:最常用的参数解析模块.
喵:Commander.js的替代品
Yargs:更复杂的参数解析(重).
Vorpal.js:带有参数解析的成熟/交互式命令行应用程序.
gor*_*gor 122
查看optimist库,它比手动解析命令行选项要好得多.
更新
Optimist已被弃用.尝试yargs,这是乐观主义者的活跃分支.
Pau*_*eld 92
这里有几个很好的答案,但这一切似乎都非常复杂.这与bash脚本访问参数值的方式非常相似,并且已经像mooGoo指出的那样已经为node.js提供了标准.(只是为了让那些对node.js不熟悉的人理解)
例:
$ node yourscript.js banana monkey
var program_name = process.argv[0]; //value will be "node"
var script_path = process.argv[1]; //value will be "yourscript.js"
var first_value = process.argv[2]; //value will be "banana"
var second_value = process.argv[3]; //value will be "monkey"
Run Code Online (Sandbox Code Playgroud)
bal*_*ton 79
适用于定义选项,操作和参数.它还会为您生成帮助页面.
如果您喜欢回调方法,则非常适合从用户那里获取输入.
如果您喜欢发电机方法,那么非常适合从用户那里获得输入.
And*_*dri 50
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 }=` , '' );
}
Run Code Online (Sandbox Code Playgroud)
输出:
node app.jsthenargv('foo')将返回nullnode app.js --foothenargv('foo')将返回truenode app.js --foo=thenargv('foo')将返回''node app.js --foo=barthenargv('foo')将返回'bar'Sea*_*ton 46
如果您的脚本名为myScript.js,并且您想要传递名字和名字'Sean Worthington',如下所示:
node myScript.js Sean Worthington
Run Code Online (Sandbox Code Playgroud)
然后在你的脚本中你写:
var firstName = process.argv[2]; // Will be set to 'Sean'
var lastName = process.argv[3]; // Will be set to 'Worthington'
Run Code Online (Sandbox Code Playgroud)
sgm*_*nda 45
在NodeJS中解析命令行参数的最简单方法是使用stdio模块.受UNIX getopt实用程序的启发,它如下所示:
var stdio = require('stdio');
var ops = stdio.getopt({
'check': {key: 'c', args: 2, description: 'What this option means'},
'map': {key: 'm', description: 'Another description'},
'kaka': {args: 1, mandatory: true},
'ooo': {key: 'o'}
});
Run Code Online (Sandbox Code Playgroud)
如果使用此命令运行上一代码:
node <your_script.js> -c 23 45 --map -k 23 file1 file2
Run Code Online (Sandbox Code Playgroud)
然后ops对象将如下:
{ check: [ '23', '45' ],
args: [ 'file1', 'file2' ],
map: true,
kaka: '23' }
Run Code Online (Sandbox Code Playgroud)
所以你可以随意使用它.例如:
if (ops.kaka && ops.check) {
console.log(ops.kaka + ops.check[0]);
}
Run Code Online (Sandbox Code Playgroud)
也支持分组选项,因此您可以编写-om而不是-o -m.
此外,stdio可以自动生成帮助/使用输出.如果你给你打电话,ops.printHelp()你会得到以下信息:
USAGE: node something.js [--check <ARG1> <ARG2>] [--kaka] [--ooo] [--map]
-c, --check <ARG1> <ARG2> What this option means (mandatory)
-k, --kaka (mandatory)
--map Another description
-o, --ooo
Run Code Online (Sandbox Code Playgroud)
如果未给出强制选项(在错误消息之前)或错误指定(例如,如果为选项指定单个arg且需要2),则还会显示上一条消息.
npm install stdio
Run Code Online (Sandbox Code Playgroud)
Mic*_*ner 41
function getArgs () {
const args = {};
process.argv
.slice(2, process.argv.length)
.forEach( arg => {
// long arg
if (arg.slice(0,2) === '--') {
const longArg = arg.split('=');
const longArgFlag = longArg[0].slice(2,longArg[0].length);
const longArgValue = longArg.length > 1 ? longArg[1] : true;
args[longArgFlag] = longArgValue;
}
// flags
else if (arg[0] === '-') {
const flags = arg.slice(1,arg.length).split('');
flags.forEach(flag => {
args[flag] = true;
});
}
});
return args;
}
const args = getArgs();
console.log(args);
Run Code Online (Sandbox Code Playgroud)
输入
node test.js -D --name=Hello
Run Code Online (Sandbox Code Playgroud)
产量
{ D: true, name: 'Hello' }
Run Code Online (Sandbox Code Playgroud)
输入
node config/build.js -lHRs --ip=$HOST --port=$PORT --env=dev
Run Code Online (Sandbox Code Playgroud)
产量
{
l: true,
H: true,
R: true,
s: true,
ip: '127.0.0.1',
port: '8080',
env: 'dev'
}
Run Code Online (Sandbox Code Playgroud)
Llo*_*oyd 27
命令行args值得一看!
您可以使用主要标记标准设置选项(了解更多信息).这些命令都是等效的,设置相同的值:
$ example --verbose --timeout=1000 --src one.js --src two.js
$ example --verbose --timeout 1000 --src one.js two.js
$ example -vt 1000 --src one.js two.js
$ example -vt 1000 one.js two.js
Run Code Online (Sandbox Code Playgroud)
要访问这些值,首先要创建一个描述应用程序接受的选项的选项定义列表.该type属性是一个setter函数(提供的值通过此函数),使您可以完全控制接收的值.
const optionDefinitions = [
{ name: 'verbose', alias: 'v', type: Boolean },
{ name: 'src', type: String, multiple: true, defaultOption: true },
{ name: 'timeout', alias: 't', type: Number }
]
Run Code Online (Sandbox Code Playgroud)
接下来,使用commandLineArgs()解析选项:
const commandLineArgs = require('command-line-args')
const options = commandLineArgs(optionDefinitions)
Run Code Online (Sandbox Code Playgroud)
options 现在看起来像这样:
{
src: [
'one.js',
'two.js'
],
verbose: true,
timeout: 1000
}
Run Code Online (Sandbox Code Playgroud)
除了上面的典型用法,您还可以配置命令行参数以接受更高级的语法表单.
表单中基于命令的语法(git样式):
$ executable <command> [options]
Run Code Online (Sandbox Code Playgroud)
例如.
$ git commit --squash -m "This is my commit message"
Run Code Online (Sandbox Code Playgroud)
表单中的命令和子命令语法(docker style):
$ executable <command> [options] <sub-command> [options]
Run Code Online (Sandbox Code Playgroud)
例如.
$ docker run --detached --image centos bash -c yum install -y httpd
Run Code Online (Sandbox Code Playgroud)
--help可以使用命令行用法生成使用指南(通常在设置时打印).请参阅下面的示例并阅读文档以获取有关如何创建它们的说明.
典型的使用指南示例.

所述聚合物-CLI使用指南是一个很好的真实的例子.

还有很多东西需要学习,请参阅维基以获取示例和文档.
Zla*_*tko 22
有一个应用程序.好吧,模块.好吧,不止一个,可能是几百个.
Yargs是一个有趣的人,它的文档很酷.
这是github/npm页面的一个例子:
#!/usr/bin/env node
var argv = require('yargs').argv;
console.log('(%d,%d)', argv.x, argv.y);
console.log(argv._);
Run Code Online (Sandbox Code Playgroud)
输出在这里(它用破折号等读取选项,短和长,数字等).
$ ./nonopt.js -x 6.82 -y 3.35 rum
(6.82,3.35)
[ 'rum' ]
$ ./nonopt.js "me hearties" -x 0.54 yo -y 1.12 ho
(0.54,1.12)
[ 'me hearties', 'yo', 'ho' ]
Run Code Online (Sandbox Code Playgroud)
小智 18
这是我的命名参数的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)
Run Code Online (Sandbox Code Playgroud)
例:
$ node test.js foo=bar fizz=buzz
bar
buzz
Run Code Online (Sandbox Code Playgroud)
注意:当参数包含a时,自然会失败=.这仅用于非常简单的用法.
Man*_*vel 18
基于标准输入解析参数 ( --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;
})();
Run Code Online (Sandbox Code Playgroud)
命令示例
node app.js --name=stackoverflow --id=10 another-argument --text="Hello World"
Run Code Online (Sandbox Code Playgroud)
argv 的结果: console.log(argv)
{
name: "stackoverflow",
id: "10",
text: "Hello World"
}
Run Code Online (Sandbox Code Playgroud)
小智 16
在节点代码中需要内置进程库。
const {argv} = require('process')
Run Code Online (Sandbox Code Playgroud)
使用他们的参数运行程序。
$ node process-args.js one two=three four
Run Code Online (Sandbox Code Playgroud)
argv 是以下数组:
argv[0] = /usr/bin/node
argv[1] = /home/user/process-args.js
argv[2] = one
argv[3] = two=three
argv[4] = four
Run Code Online (Sandbox Code Playgroud)
mbe*_*sky 15
Nodejs团队util.parseArgs在18.3.0和16.17.0版本中添加了功能。因此,如果您使用这些或更高版本的 NodeJS,您可以使用此本机解决方案解析命令行参数。
文档中的用法示例:
const {parseArgs} = require('node:util');
const args = process.argv;
const options = {
foo: {
type: 'boolean',
short: 'f'
},
bar: {
type: 'string'
}
};
const {
values,
positionals
} = parseArgs({ args, options, allowPositionals: true });
console.log(values);
console.log(positionals);
Run Code Online (Sandbox Code Playgroud)
输出样本:
$ node parseargs.js -f --bar b
[Object: null prototype] { foo: true, bar: 'b' }
[
'/Users/mbelsky/.nvm/versions/node/v18.12.1/bin/node',
'/Users/mbelsky/parseargs.js'
]
Run Code Online (Sandbox Code Playgroud)
Jos*_*nac 11
const args = process.argv.slice(2).reduce((acc, arg) => {
let [k, v = true] = arg.split('=')
acc[k] = v
return acc
}, {})
Run Code Online (Sandbox Code Playgroud)
这个命令 node index.js count=2 print debug=false msg=hi
console.log(args) // { count: '2', print: true, debug: 'false', msg: 'hi' }
Run Code Online (Sandbox Code Playgroud)
我们可以改变
let [k, v = true] = arg.split('=')
acc[k] = v
Run Code Online (Sandbox Code Playgroud)
通过(更长)
let [k, v] = arg.split('=')
acc[k] = v === undefined ? true : /true|false/.test(v) ? v === 'true' : /[\d|\.]+/.test(v) ? Number(v) : v
Run Code Online (Sandbox Code Playgroud)
自动解析布尔值和数字
console.log(args) // { count: 2, print: true, debug: false, msg: 'hi' }
Run Code Online (Sandbox Code Playgroud)
Piy*_*gar 10
传递,解析参数是一个简单的过程.Node为您提供process.argv属性,该属性是一个字符串数组,它是调用Node时使用的参数.数组的第一个条目是Node可执行文件,第二个条目是脚本的名称.
如果您使用以下参数运行脚本
$ node args.js arg1 arg2
Run Code Online (Sandbox Code Playgroud)
文件:args.js
console.log(process.argv)
Run Code Online (Sandbox Code Playgroud)
你会得到类似的数组
['node','args.js','arg1','arg2']
Run Code Online (Sandbox Code Playgroud)
npm install ps-grab
Run Code Online (Sandbox Code Playgroud)
node greeting.js --user Abdennour --website http://abdennoor.com
Run Code Online (Sandbox Code Playgroud)
-
var grab=require('ps-grab');
grab('--username') // return 'Abdennour'
grab('--action') // return 'http://abdennoor.com'
Run Code Online (Sandbox Code Playgroud)
或类似的东西:
node vbox.js -OS redhat -VM template-12332 ;
Run Code Online (Sandbox Code Playgroud)
-
var grab=require('ps-grab');
grab('-OS') // return 'redhat'
grab('-VM') // return 'template-12332'
Run Code Online (Sandbox Code Playgroud)
proj.js
for(var i=0;i<process.argv.length;i++){
console.log(process.argv[i]);
}
Run Code Online (Sandbox Code Playgroud)
终奌站:
nodemon app.js "arg1" "arg2" "arg3"
Run Code Online (Sandbox Code Playgroud)
结果:
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.
Run Code Online (Sandbox Code Playgroud)
阐释:
0 :您的机器中的node.exe目录(C:\ Program Files \nodejs \node.exe')
1:项目文件的目录.(proj.js)
2 :你的第一个节点参数(arg1)
3 :你的节点的第二个参数(arg2)
4 :节点的第三个参数(arg3)
你的实际参数从数组的2nd索引开始argv,即process.argv[2].
如果使用简单的参数(没有键+值),则使用Set解决位置问题。
例如,两个命令将返回相同的结果:
node server.js detail json
node server.js json detail
Run Code Online (Sandbox Code Playgroud)
node server.js detail json
node server.js json detail
Run Code Online (Sandbox Code Playgroud)
然后就可以使用args.has('detail')orargs.has('json')而不用担心位置。
您可以使用命令行参数system.args.我使用下面的解决方案将参数解析为一个对象,所以我可以通过名称得到我想要的那个.
var system = require('system');
var args = {};
system.args.map(function(x){return x.split("=")})
.map(function(y){args[y[0]]=y[1]});
Run Code Online (Sandbox Code Playgroud)
现在你不需要知道参数的索引.用它就像args.whatever
注意:您应该使用命名参数
file.js x=1 y=2来使用此解决方案.
传递参数很容易,接收它们只是读取 process.argv 数组 Node 基本上可以从任何地方访问的问题。但是您肯定希望将它们作为键/值对来读取,因此您需要编写一段脚本来解释它。
Joseph Merdrignac 发布了一篇使用 reduce 的漂亮文章,但它依赖于key=value语法而不是-k valueand --key value。为了使用第二个标准,我将它改写得更丑、更久,我将其作为答案发布,因为它不适合作为评论。但它确实完成了工作。
const args = process.argv.slice(2).reduce((acc,arg,cur,arr)=>{
if(arg.match(/^--/)){
acc[arg.substring(2)] = true
acc['_lastkey'] = arg.substring(2)
} else
if(arg.match(/^-[^-]/)){
for(key of arg.substring(1).split('')){
acc[key] = true
acc['_lastkey'] = key
}
} else
if(acc['_lastkey']){
acc[acc['_lastkey']] = arg
delete acc['_lastkey']
} else
acc[arg] = true
if(cur==arr.length-1)
delete acc['_lastkey']
return acc
},{})
Run Code Online (Sandbox Code Playgroud)
使用此代码,命令node script.js alpha beta -charlie delta --echo foxtrot将为您提供以下对象
args = {
"alpha":true,
"beta":true,
"c":true,
"h":true,
"a":true,
"r":true
"l":true,
"i":true,
"e":"delta",
"echo":"foxtrot"
}
Run Code Online (Sandbox Code Playgroud)
您可以解析所有参数并检查它们是否存在.
file:parse-cli-arguments.js:
module.exports = function(requiredArguments){
var arguments = {};
for (var index = 0; index < process.argv.length; index++) {
var re = new RegExp('--([A-Za-z0-9_]+)=([A/-Za-z0-9_]+)'),
matches = re.exec(process.argv[index]);
if(matches !== null) {
arguments[matches[1]] = matches[2];
}
}
for (var index = 0; index < requiredArguments.length; index++) {
if (arguments[requiredArguments[index]] === undefined) {
throw(requiredArguments[index] + ' not defined. Please add the argument with --' + requiredArguments[index]);
}
}
return arguments;
}
Run Code Online (Sandbox Code Playgroud)
不仅仅是:
var arguments = require('./parse-cli-arguments')(['foo', 'bar', 'xpto']);
Run Code Online (Sandbox Code Playgroud)
没有库的 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);
Run Code Online (Sandbox Code Playgroud)
输入:ts-node index.js -p param --parameter parameter
输出:{ p: 'param ', parameter: 'parameter' }
如果您想在 vanilla JS/ES6 中执行此操作,您可以使用以下解决方案
仅适用于NodeJS > 6
const args = process.argv
.slice(2)
.map((val, i)=>{
let object = {};
let [regexForProp, regexForVal] = (() => [new RegExp('^(.+?)='), new RegExp('\=(.*)')] )();
let [prop, value] = (() => [regexForProp.exec(val), regexForVal.exec(val)] )();
if(!prop){
object[val] = true;
return object;
} else {
object[prop[1]] = value[1] ;
return object
}
})
.reduce((obj, item) => {
let prop = Object.keys(item)[0];
obj[prop] = item[prop];
return obj;
}, {});
Run Code Online (Sandbox Code Playgroud)
而这个命令
node index.js host=http://google.com port=8080 production
Run Code Online (Sandbox Code Playgroud)
将产生以下结果
console.log(args);//{ host:'http://google.com',port:'8080',production:true }
console.log(args.host);//http://google.com
console.log(args.port);//8080
console.log(args.production);//true
Run Code Online (Sandbox Code Playgroud)
ps 如果您找到更优雅的解决方案,请更正 map 和 reduce 函数中的代码,谢谢;)
小智 5
在 Node.js 中检索参数的最简单方法是通过 process.argv 数组。这是一个全局对象,您无需导入任何其他库即可使用它。您只需将参数传递给 Node.js 应用程序,就像我们之前展示的那样,并且可以通过 process.argv 数组在应用程序中访问这些参数。
process.argv 数组的第一个元素始终是指向节点可执行文件的文件系统路径。第二个元素是正在执行的 JavaScript 文件的名称。第三个元素是用户实际传递的第一个参数。
'use strict';
for (let j = 0; j < process.argv.length; j++) {
console.log(j + ' -> ' + (process.argv[j]));
}
Run Code Online (Sandbox Code Playgroud)
该脚本所做的只是循环遍历 process.argv 数组并打印索引以及存储在这些索引中的元素。如果您对收到的参数以及参数的顺序有疑问,这对于调试非常有用。
您还可以使用 yargs 等库来处理 commnadline 参数。
虽然上面的答案很完美,而且有人已经建议了 yargs,但使用这个包真的很容易。这是一个很好的包,它使向命令行传递参数变得非常容易。
npm i yargs
const yargs = require("yargs");
const argv = yargs.argv;
console.log(argv);
Run Code Online (Sandbox Code Playgroud)
请访问https://yargs.js.org/了解更多信息。
| 归档时间: |
|
| 查看次数: |
1137155 次 |
| 最近记录: |