Skip to content

Instantly share code, notes, and snippets.

@JosePedroDias
Last active April 18, 2020 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosePedroDias/1b6e6cd82dc843f0811454fe0075b79d to your computer and use it in GitHub Desktop.
Save JosePedroDias/1b6e6cd82dc843f0811454fe0075b79d to your computer and use it in GitHub Desktop.
jsonl as generators
const fs = require('fs');
const readline = require('readline');
async function* readJsonlGen(filename) {
const lineReader = readline.createInterface({
input: fs.createReadStream(filename),
});
let i = 0;
for await (const line of lineReader) {
if (i === 0 && line === '') {
continue;
}
yield JSON.parse(line);
++i;
}
}
function* writeJsonlGen(filename) {
const logger = fs.createWriteStream(filename, {
flags: 'a',
});
while (true) {
const o = yield;
logger.write('\n' + JSON.stringify(o));
}
}
module.exports = { readJsonlGen, writeJsonlGen };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment