Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
nodejs: Detecting multiple occurrence of same string in file

In nodejs is it possible to detect multiple occurrences of the same string in a txt file?

My current code is as below

const fs = require('fs');
var file_path = 'file.txt';
fs.readFile(file_path, "UTF-8", (error, data) => {
    if (error) throw error;
    else {
        if (data.includes('Test Value')) {
            console.log(data.indexOf('Test Value'))
        }
        fs.close(file, (err) => {
            if (err)
                console.error('Failed to close file', err);
            else {
                console.log("\n> File Closed successfully");
            }
        });
    }
});

In file.txt, I have below contents

Value1
Value2
Test Value
Value3
Test Value
Value4

when I run the above code, I could only detect first occurrence of 'Test Value' whereas I need to detect all occurrences of 'Test Value' in file.txt, please help

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

indexOf has two parameters. You can use store the last position and continue the next search at the next position:

const fs = require('fs');
var file_path = 'file.txt';
fs.readFile(file_path, "UTF-8", (error, data) => {
    if (error) throw error;
    else {
        
        for (let pos = data.indexOf('Test Value'); pos > -1; pos = data.indexOf('Test Value', pos + 1)) {
            console.log(pos);
        }
        fs.close(file, (err) => {
            if (err)
                console.error('Failed to close file', err);
            else {
                console.log("\n> File Closed successfully");
            }
        });
    }
});

Example:

const data = `Value1
Value2
Test Value
Value3
Test Value
Value4`;

for (let pos = data.indexOf('Test Value'); pos > -1; pos = data.indexOf('Test Value', pos + 1)) {
    console.log(pos);
}

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use a regexp global search (multiple matches) with the RegExp .exec() method.

A global search using the String .match() method returns just the matches without the index. However the RegExp .exec() method returns the index.

let match;
let search = /Test Value/g; // <-- the 'g' flag is important!

// If you need to construct the regexp dynamically
// do = new RegExp('Test Value', 'g')

while (match = search.exec(data)) {
    console.log(match.index);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Yes. Loop through the data array and check each data element.

const fs = require('fs');
var file_path = 'file.txt';
fs.readFile(file_path, "UTF-8", (error, data) => {
    if (error) throw error;
    else {
        data.split('\n').forEach(line => {
            if (line === 'Test Value') {
                console.log(data.indexOf(line))
            }
        })
        fs.close(file, (err) => {
            if (err)
                console.error('Failed to close file', err);
            else {
                console.log("\n> File Closed successfully");
            }
        });
    }
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda