我们要用Node.js写脚本的话,第一件事要处理的就是命令行参数。
就像下面的C++代码一样,命令行参数通过argc和argv传进来。
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
cout <<"argc="<<argc<<endl;
cout << "Hello world!" << endl;
return 0;
}
我们翻译成Node语句,差不多是下面这样:
(function main() {
var argc = process.argv.length;
console.log(argc);
console.log(process.argv);
console.log('Hello,World');
process.exit(0);
})();
我们开始看看幕后英雄process模块,这其中包含了写普通代码中最重要的一些信息。这个模块是个全局的模块,可以在任意处访问。
通过下面的属性,可以获取架构、平台、命令行参数、环境变量等运行信息
先用process.hrtime()函数打个桩,存起来。运行完要计时的代码之后,将保存的值做为参数再调用process.hrtime()函数,请参照下面的示例:
var timeStart = process.hrtime();
//要计时的代码
var spendTime = process.hrtime(timeStart);
console.log(spendTime);
console.log("Cost time:" + (spendTime[0] * 1000 + spendTime[1] / 1000 / 1000) + "ms");
hrtime()返回值是一个列表,第1个元素是秒,第2个元素是纳秒。
通过process.memoryUsage()来查看
例:
console.log(process.memoryUsage());
输出的结果类似于这样:
{ rss: 19107840, heapTotal: 9587968, heapUsed: 4867064 }
我们学习了头两讲之后,下面用一个小例子来练习一下吧。需求是这样的,我用MarkDown格式写的文章,想转换成Confluence的格式。
我们只是说明一下Node.js写命令行应用的写法,将业务模型简化一下,只管这样的格式符的替换:
{
"^```java": "{code:java}",
"^```js": "{code:js}",
"^#### ": "h6. ",
"^### ": "h5. ",
"^## ": "h3. ",
"^# ": "h1. ",
"^```cpp": "{code:cpp}",
"^```python": "{code:python}",
"^```r": "{code:r}",
"^```ruby": "{code:ruby}",
"^```": "{code}",
}
综合前面所讲的按行读文件和处理命令行参数的功能,通过字符串替换实现这个需求。
(function md2docs() {
"use strict"
const readline = require('readline')
const fs = require("fs");
const file_out = "./out-" + (new Date()).getTime() + ".confluence"
var file_input;
if (process.argv.length <= 2) {
console.log("Usage:" + process.argv[0] + " " + process.argv[1] + " filename.md");
process.exit(1);
} else {
file_input = process.argv[2];
}
var timeStart = process.hrtime();
const r1 = readline.createInterface({
input: fs.createReadStream(file_input)
});
r1.on('line', (line) => {
if (!markdown2docs(line)) {
fs.appendFileSync(file_out, line + "\n");
}
});
var spendTime = process.hrtime(timeStart);
console.log(spendTime);
console.log("Cost time:" + (spendTime[0] * 1000 + spendTime[1] / 1000 / 1000) + "ms");
function markdown2docs(line) {
const md2docMap = {
"^```java": "{code:java}",
"^```js": "{code:js}",
"^#### ": "h6. ",
"^### ": "h5. ",
"^## ": "h3. ",
"^# ": "h1. ",
"^```cpp": "{code:cpp}",
"^```python": "{code:python}",
"^```r": "{code:r}",
"^```ruby": "{code:ruby}",
"^```": "{code}",
}
var mdkeys = Object.keys(md2docMap);
for (let i = 0; i < mdkeys.length; i++) {
let key = mdkeys[i];
let re = new RegExp(key);
re.compile(re);
if (re.test(line)) {
let docLine = line.replace(re, md2docMap[key]);
fs.appendFileSync(file_out, docLine + "\n");
console.log(docLine);
return true;
}
}
};
})();