-
Notifications
You must be signed in to change notification settings - Fork 29.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Readline: emit data events along with current line events #23032
Comments
related: #18904 |
Duplicate of #18603 |
@caub I was trying to make some workaround with an intermediate async generator that splits chunks and yields a Promise for each line, but such implementation was very slow, maybe due to many Promises involved. So I've made a shift with an intermediate async generator that splits chunks and yields a Promise for an Array with lines from the chunk, for now. This implementation preserves line ending characters. If I need any granular line processing or transformation, I can use any Array functions (filter, map etc) on the consuming end.
'use strict';
const { createReadStream } = require('fs');
module.exports = async function* readLines(path, encoding = 'utf8') {
const readable = createReadStream(path, encoding);
let remainder = '';
for await (const chunk of readable) {
const lines = (remainder === '' ? chunk : `${remainder}${chunk}`)
.split(/(?<=\r?\n|\r(?!\n))/u);
remainder = lines[lines.length - 1].endsWith('\n') ? '' : lines.pop();
yield lines;
}
if (remainder !== '') yield [remainder];
};
'use strict';
const { openSync, writeSync } = require('fs');
const readLines = require('./read-lines-module.js');
const output = openSync('big-file-copy.txt', 'w');
(async function main() {
try {
for await (const lines of readLines('big-file.txt')) {
writeSync(output, lines.join(''));
}
} catch (err) {
console.error(err);
}
})(); |
interesting, it makes sense so (keeping the line returns also, since 'data' event should just chunk the content) edit: I thought your snippet was what nodejs core would adopt, sry got confused, and hoping for https://github.com/nodejs/node/pull/18904/files to get merged soon |
It'd be great if
readline
could emit'data'
events for each line, so thatfor await
could be used:The text was updated successfully, but these errors were encountered: