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

时间:2017-07-16 15:30:49

标签: javascript node.js file text io

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

2 个答案:

答案 0 :(得分:1)

您必须要求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


});

答案 1 :(得分:0)

我不建议使用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
    });
})

同样,这不是很有效,所以你自担风险:)