anon20010813
anon20010813

Reputation: 155

Remove a line of text in a txt file in JavaScript

I have a program that reads specific lines of a text file with JavaScript and it works fine. What I was trying to add was functionality to remove that line of text after being printed. Is there some sort of remove line command in fs JavaScript.

function get_line(filename, line_no, callback) {
    var stream = fs.createReadStream(filename, {
        flags: 'r',
        encoding: 'utf-8',
        fd: null,
        mode: 0666,
        bufferSize: 64 * 1024
    });

    var fileData = '';
    stream.on('data', function (data) {
        fileData += data;

        // The next lines should be improved
        var lines = fileData.split("\n");

        if (lines.length >= +line_no) {
            stream.destroy();
            callback(null, lines[+line_no]);
        }
    });

    stream.on('error', function () {
        callback('Error', null);
    });

    stream.on('end', function () {
        callback('File end reached without finding line', null);
    });

}

get_line('./filePath', 2, function (err, line) {
    console.log('The line: ' + line);
    //something like this
    var newValue = replace(line, '');
    fs.writeFileSync("./filePath", newValue, 'utf-8');
})

Upvotes: 0

Views: 163

Answers (1)

user15770830
user15770830

Reputation:

This will remove and return the line.

function remove_line(filename, line_no, callback) {
    var stream = fs.createReadStream(filename, {
        flags: 'r',
        encoding: 'utf-8',
        fd: null,
        mode: 0666,
        bufferSize: 64 * 1024
    });

    var fileData = '';
    stream.on('data', function (data) {
        fileData += data;

        // The next lines should be improved
        var lines = fileData.split("\n");

        if (lines.length >= +line_no) {
            stream.destroy();
            const line = lines[+line_no];
            lines.splice(+line_no, 1);
            fs.writeFileSync(filename, lines.join("\n");
            callback(null, line);
        }
    });

    stream.on('error', function () {
        callback('Error', null);
    });

    stream.on('end', function () {
        callback('File end reached without finding line', null);
    });

}

Upvotes: 1

Related Questions