Home > Software design >  Deleting a line in a txt file with Node.js
Deleting a line in a txt file with Node.js

Time:07-05

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 :)

CodePudding user response:

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")
  })
})

CodePudding user response:

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);
}

  • Related