《Node.js 硬實戰(zhàn)》筆記

這是看《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)用 httpget() 方法,發(fā)送一個 GET 請求,返回結(jié)果丟給 myStream
  • 最后給 myStream 注冊一個是事件 total,觸發(fā)該事件會調(diào)用 on 方法的第二個參數(shù),這個參數(shù)是個回調(diào)函數(shù)。
  • 代碼
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容