《Node.js 硬实战》笔记

2017-11-25  本文已影响0人  鐘濤

这是看《Node.js 硬实战》写的第一个 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);
    }
}

上面的代码写了什么?

//  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);
})

那这个呢,写了什么?

上一篇 下一篇

猜你喜欢

热点阅读