将通过node运行时候的参数转换为对象,然后进行后续的处理
"use strict";
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs-extra"));
var _ = require("underscore");
function parseCmdLineArgs(args /*: Array<string>*/) /*: Object*/ {
var ARGUMENT_WITH_PREFIX_REGEX = /^--(\w+)=(.*)/;
var cmdLineArgsParsed = args
.map(function(arg) {
return arg.match(ARGUMENT_WITH_PREFIX_REGEX);
})
.reduce(function(argsObject, matchedContents) {
argsObject[matchedContents[1]] = matchedContents[2]; //matchedContents[1] ===(\w+) and matchedContents[2] = (.*) above
return argsObject;
}, {});
console.warn("Parsed cmd line arguments: %s", JSON.stringify(cmdLineArgsParsed));
return cmdLineArgsParsed
}
var runningAsScript = require.main === module;
if (runningAsScript) {
var parsedArgs = parseCmdLineArgs(process.argv.slice(2, process.argv.length));
}
当代码按如下运行时候(test.js 文件包含如上代码)
node test.js --max_old_space_size=800 --max_semi_space_size=1
得到的parsedArgs结果如下
{”max_old_space_size“:800, ”max_semi_space_size“:1}