Repository navigation
Expand file tree
/
Copy pathshared.js
More file actions
58 lines (44 loc) · 1.41 KB
/
Copy pathshared.js
File metadata and controls
58 lines (44 loc) · 1.41 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
50
51
52
53
54
55
56
57
58
import { once } from 'events';
import { createReadStream } from 'fs';
import { createInterface } from 'readline';
export async function processLineByLine(id) {
console.time(id)
const fileStream = createReadStream('file.csv')
const rl = createInterface({
input: fileStream,
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.
crlfDelay: Infinity,
})
rl.on('line', (line) => {
// console.log(`Line from file: ${line}`)
})
await once(rl, 'close')
console.timeEnd(id)
return 'finished'
}
export async function processByChunks(id) {
console.time(id)
// CSV files need to end with a new line
// We're working with a buffer of 64KiB (default value)
const fileStream = createReadStream('file.csv', { highWaterMark: 64 * 1024 })
let unprocessed = ''
fileStream.on('data', (chunk) => {
const chunkString = unprocessed + chunk.toString()
let start = 0
for (let index = start; index < chunkString.length; ++index) {
if (chunkString[index] === '\n') {
// const line = chunkString.slice(start, index - 1) // Remove \r at the end
start = index + 1
}
}
if (chunkString[chunkString.length - 1] !== '\n') {
unprocessed = chunkString.slice(start)
} else {
unprocessed = ''
}
})
await once(fileStream, 'end')
console.timeEnd(id)
return 'finished'
}