Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

370
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda