简体   繁体   English

如何使用Java脚本删除文本(.txt)文件中的最后一行

[英]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? Firstthird使用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. 您可以使用split将文件拆分为行数组,然后删除所需的任何行,然后使用join将数组重新join为字符串,然后写入文件。

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. 如果您使用的是非Windows平台,则可以运行unix tail命令。 If on windows, you can look at read-last-lines . 如果在Windows上,则可以查看read-last-lines

Look at this excellent answer 看这个好答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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