Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

369
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!