這是看《Node.js 硬實戰(zhàn)》寫的第一個 demo
// stream.js
const Writable = require('stream').Writable;
const util = require('util');
module.exports = class MyStream extends Writable {
constructor(matchText, options) {
super();
this.count = 0;
this.matcher = new RegExp(matchText, 'ig');
}
write(chunk, encoding, cb) {
let matches = chunk.toString().match(this.matcher);
if (matches) {
this.count += matches.length;
}
if (cb) {
cb();
}
}
end() {
this.emit('total', this.count);
}
}
上面的代碼寫了什么?
- 用
require方法導(dǎo)入了 Node.js 的兩個核心模塊:stream、util。 - 用
module.exports導(dǎo)出MyStream類。-
MyStream類繼承了Writable類。 - 覆蓋了父類
Writable的兩個方法_write()、end()。
-
// index.js
const MyStream = require('./stream');
const http = require('http');
let myStream = new MyStream('node.js');
http.get('http://chenzhongtao.cn', function (res) {
res.pipe(myStream);
})
myStream.on('total', function (count) {
console.log('test:', count);
})
那這個呢,寫了什么?
- 同樣的用
require方法導(dǎo)入模塊,其中MyStream是我自己寫的模塊。 - 然后我創(chuàng)建了
MyStream類的實例,并傳入字符串node.js初始化了該實例。 - 調(diào)用
http的get()方法,發(fā)送一個 GET 請求,返回結(jié)果丟給myStream。 - 最后給
myStream注冊一個是事件total,觸發(fā)該事件會調(diào)用on方法的第二個參數(shù),這個參數(shù)是個回調(diào)函數(shù)。 - 代碼