-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpracticalExample.mjs
79 lines (63 loc) · 1.62 KB
/
practicalExample.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { pipeline, Readable, Writable, Transform } from 'stream';
import { promisify } from 'util';
import { createWriteStream } from 'fs';
// Pipeline returns a callback, so we promisify it
const pipelineAsync = promisify(pipeline);
// Process 01
{
const readableStream = Readable({
read: function () {
this.push('Test1');
this.push('Test2');
this.push('Test3');
// Ends data
this.push(null);
},
});
const writableStream = Writable({
write(chunk, encoding, cb) {
console.log('msg', chunk.toString()); // Chunk returns a Buffer
cb();
},
});
await pipelineAsync(readableStream, writableStream);
console.log('Process 01 finished');
}
// Process 02
{
const readableStream = Readable({
read() {
for (let index = 0; index < 1e5; index++) {
const person = { id: Date.now() + index, name: `TestName-${index}` };
const data = JSON.stringify(person);
this.push(data);
}
// Ends data
this.push(null);
},
});
const writableToCSV = Transform({
transform(chunk, encoding, cb) {
const data = JSON.parse(chunk);
const result = `${data.id},${data.name.toUpperCase()}\n`;
// cb(error, sucess)
cb(null, result);
},
});
const setHeader = Transform({
transform(chunk, encoding, cb) {
this.counter = this.counter ?? 0;
if (this.counter > 0) {
return cb(null, chunk);
}
this.counter += 1;
cb(null, 'id,name\n'.concat(chunk));
},
});
await pipelineAsync(
readableStream,
writableToCSV,
setHeader,
createWriteStream('my.csv'),
);
}