[英]How do I pass command line arguments to a Node.js program?
我有一個用 Node.js 編寫的web服務器,我想用一個特定的文件夾啟動。 我不確定如何訪問 JavaScript 中的 arguments。我正在這樣運行節點:
$ node server.js folder
這里server.js
是我的服務器代碼。 Node.js 幫助說這是可能的:
$ node -h
Usage: node [options] script.js [arguments]
我將如何訪問 JavaScript 中的那些 arguments? 不知何故,我無法在 web 上找到此信息。
參數存儲在process.argv
process.argv
是一個包含命令行參數的數組。 第一個元素將是“節點”,第二個元素將是 JavaScript 文件的名稱。 下一個元素將是任何其他命令行參數。
// 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
為了像常規 javascript 函數一樣規范化參數,我在我的 node.js shell 腳本中執行此操作:
var args = process.argv.slice(2);
請注意,第一個 arg 通常是 nodejs 的路徑,第二個 arg 是您正在執行的腳本的位置。
最新的正確答案是使用minimist庫。 我們曾經使用node-optimist,但它已被棄用。
以下是直接從 minimist 文檔中獲取的如何使用它的示例:
var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);
——
$ node example/parse.js -a beep -b boop
{ _: [], a: 'beep', b: 'boop' }
——
$ 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' }
const args = process.argv;
console.log(args);
這將返回:
$ node server.js one two=three four
['node', '/home/server.js', 'one', 'two=three', 'four']
Minimist :用於最小參數解析。
Commander.js :最常用於參數解析的模塊。
Meow :Commander.js 的輕量級替代品
Yargs :更復雜的參數解析(重)。
Vorpal.js :具有參數解析的成熟/交互式命令行應用程序。
這里有幾個很好的答案,但這一切似乎都很復雜。 這與 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"
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);
輸入
node test.js -D --name=Hello
輸出
{ D: true, name: 'Hello' }
輸入
node config/build.js -lHRs --ip=$HOST --port=$PORT --env=dev
輸出
{
l: true,
H: true,
R: true,
s: true,
ip: '127.0.0.1',
port: '8080',
env: 'dev'
}
在 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, required: true},
'ooo': {key: 'o'}
});
如果您使用此命令運行前面的代碼:
node <your_script.js> -c 23 45 --map -k 23 file1 file2
然后ops
對象將如下所示:
{ check: [ '23', '45' ],
args: [ 'file1', 'file2' ],
map: true,
kaka: '23' }
所以你可以隨意使用它。 例如:
if (ops.kaka && ops.check) {
console.log(ops.kaka + ops.check[0]);
}
還支持分組選項,因此您可以編寫-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
如果未給出強制選項(在錯誤消息之前)或錯誤指定(例如,如果您為選項指定單個 arg 而它需要 2),也會顯示上一條消息。
npm install stdio
如果您的腳本名為 myScript.js 並且您希望將名字和姓氏“Sean Worthington”作為參數傳遞,如下所示:
node myScript.js Sean Worthington
然后在你的腳本中你寫:
var firstName = process.argv[2]; // Will be set to 'Sean'
var lastName = process.argv[3]; // Will be set to 'Worthington'
命令行參數值得一看!
您可以使用主要符號標准設置選項( 了解更多)。 這些命令都是等效的,設置相同的值:
$ 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
要訪問這些值,首先創建一個選項定義列表,描述您的應用程序接受的選項。 type
屬性是一個 setter 函數(提供的值通過 this 傳遞),使您可以完全控制接收到的值。
const optionDefinitions = [
{ name: 'verbose', alias: 'v', type: Boolean },
{ name: 'src', type: String, multiple: true, defaultOption: true },
{ name: 'timeout', alias: 't', type: Number }
]
接下來,使用commandLineArgs()解析選項:
const commandLineArgs = require('command-line-args')
const options = commandLineArgs(optionDefinitions)
options
現在看起來像這樣:
{
src: [
'one.js',
'two.js'
],
verbose: true,
timeout: 1000
}
除了上述典型用法,您還可以配置 command-line-args 以接受更高級的語法形式。
形式為基於命令的語法(git 風格):
$ executable <command> [options]
例如。
$ git commit --squash -m "This is my commit message"
形式的命令和子命令語法(docker 風格):
$ executable <command> [options] <sub-command> [options]
例如。
$ docker run --detached --image centos bash -c yum install -y httpd
可以使用command-line-usage生成使用指南(通常在設置--help
時打印)。 請參閱下面的示例並閱讀文檔以了解如何創建它們。
一個典型的使用指南示例。
聚合物 cli使用指南是一個很好的現實例子。
還有很多東西要學習,請參閱wiki以獲取示例和文檔。
這是我的命名參數的 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
注意:當參數包含=
時,這自然會失敗。 這僅用於非常簡單的用法。
有一個應用程序。 嗯,模塊。 嗯,不止一個,可能是數百個。
Yargs是其中之一,它的文檔讀起來很酷。
這是來自 github/npm 頁面的示例:
#!/usr/bin/env node
var argv = require('yargs').argv;
console.log('(%d,%d)', argv.x, argv.y);
console.log(argv._);
輸出在這里(它讀取帶有破折號等,短和長,數字等的選項)。
$ ./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' ]
基於標准輸入解析參數( --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;
})();
命令示例
node app.js --name=stackoverflow --id=10 another-argument --text="Hello World"
argv 的結果: console.log(argv)
{
name: "stackoverflow",
id: "10",
text: "Hello World"
}
項目.js
for(var i=0;i<process.argv.length;i++){
console.log(process.argv[i]);
}
終端:
nodemon app.js "arg1" "arg2" "arg3"
結果:
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.
說明:
C:\\Program Files\\nodejs\\node.exe
)proj.js
)arg1
)的第一個參數arg2
)的第二個參數arg3
) 您的實際參數從argv
數組的第二個索引開始,即process.argv[2]
。
const args = process.argv.slice(2).reduce((acc, arg) => {
let [k, v = true] = arg.split('=')
acc[k] = v
return acc
}, {})
對於此命令node index.js count=2 print debug=false msg=hi
console.log(args) // { count: '2', print: true, debug: 'false', msg: 'hi' }
我們可以改變
let [k, v = true] = arg.split('=')
acc[k] = v
通過(更長的時間)
let [k, v] = arg.split('=')
acc[k] = v === undefined ? true : /true|false/.test(v) ? v === 'true' : /[\d|\.]+/.test(v) ? Number(v) : v
自動解析布爾值和數字
console.log(args) // { count: 2, print: true, debug: false, msg: 'hi' }
傳遞、解析參數是一個簡單的過程。 Node 為您提供 process.argv 屬性,它是一個字符串數組,是調用 Node 時使用的參數。 數組的第一個條目是 Node 可執行文件,第二個條目是腳本的名稱。
如果您使用以下參數運行腳本
$ node args.js arg1 arg2
文件:args.js
console.log(process.argv)
你會得到像
['node','args.js','arg1','arg2']
使用nconf https://github.com/flatiron/nconf之類的集中方式來管理您的配置可能是一個好主意
它可以幫助您使用配置文件,環境變量,命令行參數。
在節點代碼中需要內置的進程庫。
const {argv} = require('process')
使用他們的 arguments 運行程序。
$ 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
npm install ps-grab
node greeting.js --user Abdennour --website http://abdennoor.com
——
var grab=require('ps-grab');
grab('--username') // return 'Abdennour'
grab('--action') // return 'http://abdennoor.com'
或類似的東西:
node vbox.js -OS redhat -VM template-12332 ;
——
var grab=require('ps-grab');
grab('-OS') // return 'redhat'
grab('-VM') // return 'template-12332'
您可以使用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=1 y=2
這樣的命名參數來使用這個解決方案。
您可以解析所有參數並檢查它們是否存在。
文件:解析-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;
}
不僅僅是做:
var arguments = require('./parse-cli-arguments')(['foo', 'bar', 'xpto']);
傳遞參數很容易,接收它們只是讀取 process.argv 數組 Node 基本上可以從任何地方訪問的問題。 但是您肯定希望將它們作為鍵/值對來讀取,因此您需要編寫一段腳本來解釋它。
Joseph Merdrignac 發布了一個使用 reduce 的漂亮的,但它依賴於key=value
語法而不是-k value
和--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
},{})
使用此代碼,命令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"
}
如果您想在 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;
}, {});
而這個命令
node index.js host=http://google.com port=8080 production
將產生以下結果
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
ps 如果您找到更優雅的解決方案,請更正 map 和 reduce 函數中的代碼,謝謝;)
雖然上面的答案很完美,而且有人已經建議了 yargs,但使用這個包真的很容易。 這是一個很好的包,它使向命令行傳遞參數變得非常容易。
npm i yargs
const yargs = require("yargs");
const argv = yargs.argv;
console.log(argv);
請訪問https://yargs.js.org/了解更多信息。
沒有庫的 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 --parameter parameter
輸出: { p: 'param ', parameter: 'parameter' }
在 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]));
}
這個腳本所做的就是遍歷 process.argv 數組並打印索引以及存儲在這些索引中的元素。 如果您質疑您收到的參數以及順序,這對於調試非常有用。
您還可以使用像 yargs 這樣的庫來處理 commnadline 參數。
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 }=` , '' );
}
輸出:
node app.js
調用,則argv('foo')
將返回null
node app.js --foo
調用,則argv('foo')
將返回true
node app.js --foo=
調用,則argv('foo')
將返回''
node app.js --foo=bar
調用,則argv('foo')
將返回'bar'
NodeJS 公開了一個名為process
的全局變量。
我們可以用:
process.argv
獲取命令行 arguments 傳遞給我們的腳本。
process.argv
的 output 將是一個按以下順序排列的列表:
[
full-path-to-node-executable,
full-path-to-the-script-file
...additonal-arguments-we-provide
]
process.argv
是您的朋友,Node JS 本身支持捕獲命令行參數。 請參閱下面的示例::
process.argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
})
ES6 風格的無依賴解決方案:
const longArgs = arg => {
const [ key, value ] = arg.split('=');
return { [key.slice(2)]: value || true }
};
const flags = arg => [...arg.slice(1)].reduce((flagObj, f) => ({ ...flagObj, [f]: true }), {});
const args = () =>
process.argv
.slice(2)
.reduce((args, arg) => ({
...args,
...((arg.startsWith('--') && longArgs(arg)) || (arg[0] === '-' && flags(arg)))
}), {});
console.log(args());
我擴展了getArgs
函數只是為了獲取命令,以及標志( -f
, --anotherflag
)和命名參數( --data=blablabla
):
/**
* @module getArgs.js
* get command line arguments (commands, named arguments, flags)
*
* @see https://stackoverflow.com/a/54098693/1786393
*
* @return {Object}
*
*/
function getArgs () {
const commands = []
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
})
}
else {
// commands
commands.push(arg)
}
})
return { args, commands }
}
// test
if (require.main === module) {
// node getArgs test --dir=examples/getUserName --start=getUserName.askName
console.log( getArgs() )
}
module.exports = { getArgs }
$ node lib/getArgs test --dir=examples/getUserName --start=getUserName.askName
{
args: { dir: 'examples/getUserName', start: 'getUserName.askName' },
commands: [ 'test' ]
}
$ node lib/getArgs --dir=examples/getUserName --start=getUserName.askName test tutorial
{
args: { dir: 'examples/getUserName', start: 'getUserName.askName' },
commands: [ 'test', 'tutorial' ]
}
您可以從process.argv()獲取命令行信息
而且我不想將問題限制在node.js
。 相反,我想把它變成如何將字符串解析為參數。
console.log(ArgumentParser(`--debug --msg="Hello World" --title="Test" --desc=demo -open --level=5 --MyFloat=3.14`))
輸出
{
"debug": true,
"msg": "Hello World",
"title": "Test",
"desc": "demo",
"open": true,
"level": 5,
"MyFloat": 3.14
}
純javascript,不需要依賴
// 👇 Below is Test (() => { window.onload = () => { const testArray = [ `--debug --msg="Hello World" --title="Test" --desc=demo -open --level=5 --MyFloat=3.14`, ] for (const testData of testArray) { try { const obj = ArgumentParser(testData) console.log(obj) } catch (e) { console.error(e.message) } } } })() // 👇 Script class ParserError extends Error { } function Cursor(str, pos) { this.str = str this.pos = pos this.MoveRight = (step = 1) => { this.pos += step } this.MoveToNextPara = () => { const curStr = this.str.substring(this.pos) const match = /^(?<all> *--?(?<name>[a-zA-Z_][a-zA-Z0-9_]*)(=(?<value>[^-]*))?)/g.exec(curStr) // https://regex101.com/r/k004Gv/2 if (match) { let {groups: {all, name, value}} = match if (value !== undefined) { value = value.trim() if (value.slice(0, 1) === '"') { // string if (value.slice(-1) !== '"') { throw new ParserError(`Parsing error: '"' expected`) } value = value.slice(1, -1) } else { // number or string (without '"') value = isNaN(Number(value)) ? String(value) : Number(value) } } this.MoveRight(all.length) return [name, value ?? true] // If the value is undefined, then set it as ture. } throw new ParserError(`illegal format detected. ${curStr}`) } } function ArgumentParser(str) { const obj = {} const cursor = new Cursor(str, 0) while (1) { const [name, value] = cursor.MoveToNextPara() obj[name] = value if (cursor.pos === str.length) { return obj } } }
Nodejs 團隊在版本 18.3.0 和 16.17.0 中添加了util.parseArgs
function。 因此,如果您使用這些或更高版本的 nodejs,則可以使用此本機解決方案解析命令行 arguments。
文檔中的用法示例:
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);
Output 樣本:
$ 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'
]
如節點文檔中所述 process.argv 屬性返回一個數組,其中包含啟動 Node.js 進程時傳遞的命令行參數。
例如,假設 process-args.js 有以下腳本:
// print process.argv
process.argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});
以如下方式啟動 Node.js 進程:
$ node process-args.js one two=three four
將生成輸出:
0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four
大多數人都給出了很好的答案。 我也想在這里貢獻一些東西。 我正在使用lodash
庫提供答案,以遍歷我們在啟動應用程序時傳遞的所有命令行參數:
// Lodash library
const _ = require('lodash');
// Function that goes through each CommandLine Arguments and prints it to the console.
const runApp = () => {
_.map(process.argv, (arg) => {
console.log(arg);
});
};
// Calling the function.
runApp();
要運行上面的代碼,只需運行以下命令:
npm install
node index.js xyz abc 123 456
結果將是:
xyz
abc
123
456
將命令行參數傳遞給Node.js程序的最佳方法是使用命令行界面(CLI)
您可以使用一個漂亮的npm模塊,稱為nodejs-cli 。
如果您想創建一個沒有依賴性的程序,我想在Github上創建一個程序,如果您想查看它,它實際上非常簡單易用,請單擊此處 。
如果你想使用像server -f fileURI
這樣的 unix 樣式標志,那么使用server -f fileURI
的ray-fs
庫。 它非常容易使用!
最初的問題是要求傳遞命令行參數,而不是更復雜的參數解析。 然而,對於所有復雜的答案,他們都錯過了一個簡單而有用的變化。
您知道 Unix shell 支持命名參數嗎? 這可以追溯到 1980 年代的原始 Bourne shell。 用法很簡單:
$ FOO=one BAR=two nodejs myscript.js
在 Javascript 中獲取參數:
var foo = process.env.FOO;
var bar = process.env.BAR;
一旦超過兩個或三個參數,命名參數就更容易閱讀。 可選參數簡單,順序不固定。
(這甚至可能適用於 Windows,因為最近支持 Unix shell。)
此外,令人震驚的是,很少有 Unix 程序員知道這種用法。 :)
一個簡單的片段,如果有的話需要它:
var fs = require('fs'), objMod = {};
process.argv.slice(2).map(function(y, i) {
y = y.split('=');
if (y[0] && y[1]) objMod[y[0]] = y[1];
else console.log('Error in argument number ' + (i+1));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.