Home > front end >  How can I search for multiple strings and stop when one is found?
How can I search for multiple strings and stop when one is found?

Time:10-05

So I have a piece of code, which takes a line from one text file and searches it in other text file. This is my code:

const searchStream = (filename, text) => {

    return new Promise((resolve) => {
        const inStream = fs.createReadStream(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', result)
            resolve(result)
        });
    })
}
searchStream('base_output', str1);
searchStream('base_output', str2);
searchStream('base_output', str3);

My questions are:

A. How do I perform a search of multiple strings(str1,str2,str3) because it only does it for str1 and then stops.

B. How do I make the search stop when it finds a string, e.g. searchStream('base_output', str1); -> str1 is found in text file, the search then stops and then it moves to str2, then to str3 and writes the strings, for example, to another text file.

CodePudding user response:

A) When you read a line you can search for multiple strings one by one. B) As we are using multiple if statements here rather than if else the function searchs for each string one after another. (P.S. you can read about writing to files in nodejs documentation)

const searchStream = (filename, text, text2, text3) => {
    return new Promise((resolve) => {
        const inStream = fs.createReadStream(filename   '.txt');
        const outStream = new stream;
        const rl = readline.createInterface(inStream, outStream);
        const result = [];
        const regEx = new RegExp(text, "i")
        const regEx2 = new RegExp(text2, "i")
        const regEx3 = new RegExp(text3, "i")
        rl.on('line', function (line) {
            if (line && line.search(regEx) >= 0) {
                result.push(line)
            }
            if (line && line.search(regEx2) >= 0) {
                result.push(line)
            }
             if (line && line.search(regEx3) >= 0) {
                result.push(line)
            }
        });
        rl.on('close', function () {
            console.log('finished search', result)
            resolve(result)
        });
    })
}
searchStream('base_output', str1, str2, str3);
  • Related