简体   繁体   中英

How to remove last line in the text(.txt) file using Javascript

I have:

let removeString = (fileName, strToRemove) => {
    fs.readFile(fileName, 'utf8', function(err, data){
    let toRemove = data.replace(strToRemove+'\n','')
    fs.writeFile(fileName, toRemove)
    })
};

This successfully removes non first or last line, but how do I remove from

first
second
third

First or third using fs?

You can use split to split the file into an array of lines then remove whichever line you want, then rejoin the array into a string using join then write the file.

Example:

let removeString = (fileName, strToRemove) => {
    fs.readFile(fileName, 'utf8', function(err, data){
        let splitArray = data.split('\n');
        splitArray.splice(splitArray.indexOf(strToRemove), 1);
        let result = splitArray.join('\n');
        fs.writeFile(fileName, result)
    })
};

The above solution is not optimized for a very large file as it reads the whole file. If you are on non-windows platform, you can run unix tail command. If on windows, you can look at read-last-lines .

Look at this excellent answer

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