-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
65 lines (48 loc) · 1.18 KB
/
app.js
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
import fs from "fs"
import { Readable, Transform, pipeline } from "stream";
import { promisify } from "util";
const pipelineAsync = promisify(pipeline)
{
const readableStream = new Readable({
read() {
for (let i = 0; i < 1e8; i++) {
const data = {
id: Date.now() + i,
name: `Lemuel-Pereira(${i})`
}
this.push(JSON.stringify(data))
}
this.push(null)
}
})
const writableToCsv = new Transform({
transform(chunk, encoding, cb) {
const data = JSON.parse(chunk)
cb(null, `${data.id},${data.name}\n`)
}
})
const setHeader = new Transform({
transform(chunk, encoding, cb) {
this.counter = this.counter ?? 0
if (this.counter) {
return cb(null, chunk)
}
this.counter++
const header = "id, name\n"
cb(null, header.concat(chunk))
}
})
await pipelineAsync(
readableStream,
writableToCsv,
setHeader,
fs.createWriteStream("users.csv")
)
}
{
const readableStream = fs.createReadStream("users.csv")
await pipelineAsync(
readableStream,
process.stdout
)
}