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

371
Visualizações
Deleting a line in a txt file with Node.js

I recently made a script in which I want to delete an EXACT match from a txt file with node. It print's out true but doesn't actually remove the line from the txt file. I am using discord to get the argument. I'm not sure what I'm doing wrong but here is my script:

        const fs = require('fs')
        fs.readFile('notredeemed.txt', function (err, data) {
            if (err) throw err;
                if (data.toString().match(new RegExp(`^${args[0]}$`, "m"))) {
                    fs.readFile('notredeemed.txt', 'utf8', function (err,data) {
                      if (err) {
                        return console.log(err);
                      }
                      var result = data.replace(/${args[0]/g, '');
                    
                      fs.writeFile('notredeemed.txt', result, 'utf8', function (err) {
                         if (err) return console.log(err);
                      });
                    });
                      console.log("true")

If someone could help me I would appreciate it :)

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

0

I think you can do it very similarly as your current solution, just the regex is a little off.

Instead of just using ^ and $ to indicate that the entire string starts and ends with the args[0], I used two capture groups as the delimiters of a line.

This one matches any newline character or the beginning of the string. Works for first line of file, and prevents partial replacement e.g. llo replacing Hello:

(\n|^)

And this one matches a carriage return or the end of the string. This works for cases where there is no newline at the end of the file, and also prevents Hel replacing Hello:

(\r|$)

That should ensure that you are always taking out an entire line that matches your args.

I also eliminated the second readFile as it wasn't necessary to get it to work.

const fs = require("fs")

fs.readFile("notredeemed.txt", function (err, data) {
  if (err) throw err

  const match = new RegExp(`(\n|^)${args[0]}(\r|$)`)

  const newFile = data.toString().replace(match, ``)

  fs.writeFile("notredeemed.txt", newFile, "utf8", function (err) {
    if (err) return console.log(err)
    console.log("true")
  })
})
about 4 years ago · Juan Pablo Isaza Relatório

0

Here is my solution.

Algorithm:

  1. Split the file content into individual lines with your desired End of Line Flag (generally "\n" or "\r\n")
  2. Filter all the lines that you want to delete
  3. Join all the filtered lines back together with the EOL flag

const replacingLine = "- C/C++ addons with Node-API";

const fileContent = `- V8
- WASI
- C++ addons
- C/C++ addons with Node-API
- C++ embedder API
- C/C++ addons with Node-API
- Corepack`;

const newFileContent = replace({ fileContent, replacingLine });

console.log(newFileContent);

function replace({ fileContent, replacingLine, endOfLineFlag = "\n" }) {
  return fileContent
    .split(endOfLineFlag)
    .filter((line) => line !== replacingLine)
    .join(endOfLineFlag);
}

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