Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Last active April 1, 2021 12:57
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 crazy4groovy/fb42b8e98e3bbc0bbaa4c0f8bdf8ce37 to your computer and use it in GitHub Desktop.
Save crazy4groovy/fb42b8e98e3bbc0bbaa4c0f8bdf8ce37 to your computer and use it in GitHub Desktop.
Stream: a large text file line-by-line; dir recursively (NodeJS)
const fs = require("fs");
const readline = require("readline");
const byLine = async ({file, handleLine, charset="utf8"}) => {
return new Promise((done, err) => {
if (!fs.existsSync(file)) {
return err(new Error('File not found!'));
}
const rl = readline.createInterface({
input: fs.createReadStream(file, charset),
output: process.stdout,
terminal: false,
});
rl.on("line", handleLine);
rl.on("close", done);
});
};
function handleLine(line) {...}
const file = "~/mydatafile.txt"; // +100GB!! no prob.
await byLine({file, handleLine});
const walker = require("folder-walker");
function handleFile(file) {...}
const baseFolder = "~";
const doneWalkBaseFolder = new Promise((done) => {
// recursively walk through a directory via a stream
const stream = walker([baseFolder]);
stream.on("data", handleFile);
stream.on("end", done);
});
await doneWalkBaseFolder;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment