How to remove one line from a txt file

前端 未结 2 377
迷失自我
迷失自我 2020-12-06 05:17

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

相关标签:
2条回答
  • 2020-12-06 05:34

    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.");
        });
    })
    
    0 讨论(0)
  • 2020-12-06 05:41
    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);
    });
    
    0 讨论(0)
提交回复
热议问题