我有一个大文本日志文件(大约20MB)。我想删除前15,000行左右。我怎么能在Node.js中做到这一点?
答案 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
});
})
同样,这不是很有效,所以你自担风险:)