Skip to content

Instantly share code, notes, and snippets.

@GaetanoPiazzolla
Last active October 30, 2021 17:01
Show Gist options
  • Save GaetanoPiazzolla/6e6c41e3311378447671d91917b7086d to your computer and use it in GitHub Desktop.
Save GaetanoPiazzolla/6e6c41e3311378447671d91917b7086d to your computer and use it in GitHub Desktop.
Search string in file NodeJS - using streams
const fs = require('fs');
const readline = require('readline');
const stream = require('stream');
const searchStream = (filename, text) => {
return new Promise((resolve) => {
const inStream = fs.createReadStream('file/' + filename + ".txt");
const outStream = new stream;
const rl = readline.createInterface(inStream, outStream);
const result = [];
const regEx = new RegExp(text, "i")
rl.on('line', function (line) {
if (line && line.search(regEx) >= 0) {
result.push(line)
}
});
rl.on('close', function () {
console.log('finished search', filename)
resolve(result)
});
})
}
@GaetanoPiazzolla
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment