Last active
October 30, 2021 17:01
-
-
Save GaetanoPiazzolla/6e6c41e3311378447671d91917b7086d to your computer and use it in GitHub Desktop.
Search string in file NodeJS - using streams
This file contains hidden or 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'); | |
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) | |
}); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Related to article https://medium.com/codex/achieve-the-best-performance-search-a-string-in-file-using-nodejs-6a0f2a3b6cfa