-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpipelineTransformExample.mjs
More file actions
49 lines (43 loc) · 1.21 KB
/
pipelineTransformExample.mjs
File metadata and controls
49 lines (43 loc) · 1.21 KB
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
import { pipeline, Readable, Transform } from 'stream';
import { promisify } from 'util';
import { createWriteStream } from 'fs';
/*
o pipeline funciona do mesmo modo que o pipe,
porém ele resolve problemas de vazamento de memória
e possui um método de callback */
/* o promisify permite dar um await na pipeline */
const pipelineAsync = promisify(pipeline);
const readableStream = Readable({
read () {
for ( let index = 0; index < 1e2; index++ ) {
const person = { id: Date.now() + index, name: `Ricky-${index}` };
const payload = JSON.stringify(person);
this.push(payload);
}
this.push(null);
}
})
const writableMapToCSV = Transform({
transform(chunk, enconding, callback) {
const payload = JSON.parse(chunk);
const result = `${payload.id},${payload.name.toUpperCase()}\n`;
callback(null, result);
}
})
const setHeader = Transform({
transform(chunk, enconding, callback) {
this.counter = this.counter ?? 0;
if (this.counter) {
return callback(null, chunk);
}
this.counter += 1;
callback(null, "id, name\n".concat(chunk));
}
})
await pipelineAsync(
readableStream,
writableMapToCSV,
setHeader,
// process.stdout,
createWriteStream('my.csv')
)