Skip to content

Commit 6874b50

Browse files
committed
自定义writable例子
1 parent f79c92b commit 6874b50

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
var Writable = require('stream').Writable;
2+
3+
// 自定义Writable Stream
4+
class HeaderParser extends Writable {
5+
constructor (callback) {
6+
super({});
7+
this.callback = callback;
8+
this.chunks = [];
9+
10+
this.on('finish', () => {
11+
let buff = Buffer.concat(this.chunks);
12+
let body = JSON.parse(buff.toString());
13+
this.callback( body );
14+
});
15+
}
16+
17+
_write(chunk, encoding, callback) {
18+
this.chunks.push(chunk);
19+
callback();
20+
}
21+
}
22+
23+
var http = require('http');
24+
var server = http.createServer(function (req, res) {
25+
req.pipe(new HeaderParser(function (body) {
26+
res.end(body.nick);
27+
}));
28+
});
29+
server.listen(3000);

0 commit comments

Comments
 (0)