-
Notifications
You must be signed in to change notification settings - Fork 1
/
transformStream.mjs
81 lines (69 loc) · 1.66 KB
/
transformStream.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
80
81
import { pipeline, Readable, Writable, Transform } from 'stream'
import { promisify } from 'util'
import { createWriteStream } from 'fs'
const pipelineAsync = promisify(pipeline)
{
const readableStream = Readable({
read: function () {
this.push('hello man!! 0')
this.push('hello man!! 1')
this.push('hello man!! 2')
this.push(null)
}
})
const writableStream = Writable({
write(chunk, enconding, cb) {
console.log('msg: ', chunk.toString())
cb()
}
})
await pipelineAsync(
readableStream,
// process.stdout
writableStream
)
console.log('Process 01 acabou!')
console.log('------------------')
}
{
const readableStream = Readable({
read() {
for (let index = 0; index < 1e5; index++) {
const person = {
id: Date.now() + index,
name: `Name-${index}`
}
const data = JSON.stringify(person)
this.push(data)
}
// avisa que acabou os dados
this.push(null)
}
})
const writableMapToCSV = Transform({
transform(chunk, enconding, cb) {
const data = JSON.parse(chunk)
const result = `${data.id},${data.name.toUpperCase()}\n`
cb(null, result)
}
})
const setHeader = Transform({
transform(chunk, enconding, cb) {
this.counter = this.counter ?? 0
if (this.counter) {
return cb(null, chunk)
}
this.counter += 1
cb(null, 'id,name\n'.concat(chunk))
}
})
await pipelineAsync(
readableStream,
writableMapToCSV,
setHeader,
// process.stdout
createWriteStream('my.csv')
)
console.log('Process 02 acabou!')
console.log('------------------')
}