-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
92 lines (78 loc) · 2.59 KB
/
index.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const fs = require('fs');
const readline = require('readline');
const runProfiling = require('./runProfiling');
(async () => {
await runProfiling('readline stream interface', () => new Promise((resolve, reject) => {
const rl = readline.createInterface({
input: fs.createReadStream('big.txt'),
});
let i = 0;
rl.on('line', (line) => {
i += 1;
});
rl.on('error', reject);
rl.on('close', () => {
console.log(`Read ${i} lines`);
resolve();
});
}));
await runProfiling('readline async iteration', async () => {
const rl = readline.createInterface({
input: fs.createReadStream('big.txt'),
});
let i = 0;
for await (const line of rl) {
i += 1;
}
console.log(`Read ${i} lines`);
});
// Modify readline to return an array of lines
// Copied from https://github.com/nodejs/node/blob/efec6811b667b6cf362d648bc599b667eebffce0/lib/readline.js
const lineEnding = /\r?\n|\r(?!\n)/;
readline.Interface.prototype._normalWrite = function(b) {
if (b === undefined) {
return;
}
let string = this._decoder.write(b);
if (this._sawReturnAt &&
DateNow() - this._sawReturnAt <= this.crlfDelay) {
string = string.replace(/^\n/, '');
this._sawReturnAt = 0;
}
// Run test() on the new string chunk, not on the entire line buffer.
const newPartContainsEnding = lineEnding.test(string);
if (this._line_buffer) {
string = this._line_buffer + string;
this._line_buffer = null;
}
if (newPartContainsEnding) {
this._sawReturnAt = string.endsWith('\r') ? DateNow() : 0;
// Got one or more newlines; process into "line" events
const lines = string.split(lineEnding);
// Either '' or (conceivably) the unfinished portion of the next line
string = lines.pop();
this._line_buffer = string;
this._onLine(lines); // <- changed from `for of` to `this._onLine(lines)`
} else if (string) {
// No newlines this time, save what we have for next time
this._line_buffer = string;
}
};
readline.Interface.prototype._line = function() {
const line = this._addHistory();
this.clearLine();
this._onLine([line]); // <- changed from `line` to `[line]`
};
await runProfiling('readline async iteration via array of lines', async () => {
const rl = readline.createInterface({
input: fs.createReadStream('big.txt'),
});
let i = 0;
for await (const lines of rl) {
for (const line of lines) {
i += 1;
}
}
console.log(`Read ${i} lines`);
});
})();