最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - How to remove last line in the text(.txt) file using Javascript - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited May 9, 2018 at 10:42 ImFaind asked May 9, 2018 at 10:38 ImFaindImFaind 111 silver badge4 bronze badges 5
  • I have tried your code and it did remove 'first' when calling removeString('file.txt', 'first'). – Enric A. Commented May 9, 2018 at 10:45
  • 1 Suspiciously similar question, but a different account ..? – Teemu Commented May 9, 2018 at 10:51
  • @Teemu and that one again looks like a duplicate of stackoverflow./q/50237509/1427878 ... – C3roe Commented May 9, 2018 at 11:15
  • @CBroe Indeed, all the questions were including a "[tag]" in the title too ... – Teemu Commented May 9, 2018 at 11:22
  • ... I saw [tag] in other questions – ImFaind Commented May 9, 2018 at 11:28
Add a ment  | 

2 Answers 2

Reset to default 3

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 mand. If on windows, you can look at read-last-lines.

Look at this excellent answer

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)
    })
};
发布评论

评论列表(0)

  1. 暂无评论