Search code examples
node.jsfsreadline

node.js remove a line from .txt file


If the line is "removemefromthefile" I want to delete the whole line from the .txt file. How would I do that? I have the following code:

const readline = require('readline');

    var rd = readline.createInterface({
            input: fs.createReadStream('data.txt'),
        });

        rd.on('line', function (line) {
            if (line.trim() === "removemefromthefile") {
                // remove the line
                rd.close()
            }
        })

Solution

  • Here's one way to do it,

    var fs = require('fs');
    fs.readFile('data.txt', { encoding: 'utf-8' }, function (err, data) {
        if (err) {
            throw error;
        }
    
        let dataArray = data.split('\n');
    
        for (let i = 0; i < dataArray.length; i++) {
            if (dataArray[i].trim() === 'removemefromthefile') {
                dataArray.splice(i, 1);
            }
        }
    
        const updatedData = dataArray.join('\n');
        fs.writeFile('data.txt', updatedData, (err) => {
            if (err) throw err;
            console.log('Successfully updated the file!');
        });
    });