How to remove one line from a txt file

var fs = require('fs')
fs.readFile(filename, 'utf8', function(err, data)
{
    if (err)
    {
        // check and handle err
    }
    // data is the file contents as a single unified string
    // .split('\n') splits it at each new-line character and all splits are aggregated into an array (i.e. turns it into an array of lines)
    // .slice(1) returns a view into that array starting at the second entry from the front (i.e. the first element, but slice is zero-indexed so the "first" is really the "second")
    // .join() takes that array and re-concatenates it into a string
    var linesExceptFirst = data.split('\n').slice(1).join('\n');
    fs.writeFile(filename, linesExceptFirst, function(err, data) { if (err) {/** check and handle err */} });
});

I just came across the need to be able to exclude several lines in a file. Here's how I did it with a simple node function.

const fs = require('fs');

const removeLines = (data, lines = []) => {
    return data
        .split('\n')
        .filter((val, idx) => lines.indexOf(idx) === -1)
        .join('\n');
}

fs.readFile(fileName, 'utf8', (err, data) => {
    if (err) throw err;

    // remove the first line and the 5th and 6th lines in the file
    fs.writeFile(fileName, removeLines(data, [0, 4, 5]), 'utf8', function(err) {
        if (err) throw err;
        console.log("the lines have been removed.");
    });
})

use replace

const fs = require('fs');

function readWriteSync() {
  var data = fs.readFileSync(filepath, 'utf-8');

  // replace 'world' together with the new line character with empty
  var newValue = data.replace(/world\n/, '');

  fs.writeFileSync(filepath, newValue, 'utf-8');
}

Tags:

Node.Js