简体   繁体   中英

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM