用Node.js删除前15k行的文本文件

我有一个大的文本日志文件(大约20MB)。 我想删除第一个15000行左右。 我怎么能在Node.js中做到这一点?

你必须要求readLine npm包。

const readline = require('readline'); const fs = require('fs'); const rl = readline.createInterface({ input: fs.createReadStream('sample.txt') }); rl.on('line', (line) => { console.log(`Line from file: ${line}`); //YOu can delete your line Here }); 

我不build议使用NodeJS为这个任务加载20MB的内存,但是如果你知道你在做什么,那么你可以将每行的文本拆分,然后像这样拼接它:

 const fs = require('fs'); const path = '/some/path/here'; fs.readFile(path, (err, data) => { if(err) { // check for error here } let lines = data.split('\n'); lines.splice(0, 15000); // from line 0 to 15000 let splited = lines.join('\n'); // joined it from the lines array // Do whatever you want to do here. fs.writeFile(path, splited, err => { // handle error here }); }) 

再一次,这不是真的有效率,所以在你自己的风险:)