27

I have the following text file ("test.txt") that I want to manipulate in node.js:

world
food

I want to remove the first line so that food becomes the first line instead. How can I do that?

1
  • 11
    It is a pretty legitimate question as I don't get why people downvoted it.
    – knoxgon
    Apr 21, 2017 at 6:47

3 Answers 3

36
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 */} });
});
1
  • @Jake I think I've added the necessary elaboration which might help someone for whom it's unclear. hope this helps!
    – Scott M
    Mar 25, 2020 at 3:23
6

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.");
    });
})
5

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.