Skip to content

Commit 33f5c55

Browse files
committed
Cork/uncork example
1 parent 68bbe01 commit 33f5c55

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

JavaScript/c-cork.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
'use strict';
2+
3+
const stream = require('node:stream');
4+
5+
const ENTER = 13;
6+
7+
const createBufferedStream = () => {
8+
const buffers = [];
9+
const writable = new stream.Writable({
10+
write(chunk, encoding, next) {
11+
buffers.push(chunk);
12+
next();
13+
},
14+
final(done) {
15+
const result = Buffer.concat(buffers);
16+
this.emit('result', result);
17+
done();
18+
}
19+
});
20+
return writable;
21+
};
22+
23+
const lines = createBufferedStream();
24+
25+
lines.on('result', (result) => {
26+
console.log({ result });
27+
});
28+
29+
process.stdin.setRawMode(true);
30+
process.stdin.on('data', (data) => {
31+
const key = data[0];
32+
if (key === ENTER) {
33+
lines.write(data);
34+
if (lines.writableCorked === 1) lines.uncork();
35+
lines.end();
36+
process.exit(0);
37+
} else {
38+
if (lines.writableCorked === 0) lines.cork();
39+
lines.write(data);
40+
}
41+
process.stdout.write(data);
42+
});

0 commit comments

Comments
 (0)