Last active
April 18, 2020 15:24
-
-
Save JosePedroDias/1b6e6cd82dc843f0811454fe0075b79d to your computer and use it in GitHub Desktop.
jsonl as generators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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