1
我有一個大的文本日誌文件(大約20MB)。我想刪除前面的15000行左右。我如何在Node.js中做到這一點?用Node.js刪除第一個15k行的文本文件
我有一個大的文本日誌文件(大約20MB)。我想刪除前面的15000行左右。我如何在Node.js中做到這一點?用Node.js刪除第一個15k行的文本文件
你必須要求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
});
我不會推薦20MB加載到內存使用此的NodeJS任務,但如果你知道你正在做,那麼你可以通過分割每行文字是什麼,然後拼接它像這樣:
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
});
})
再一次,這不是真的高效,所以在你自己的風險:)
與殼只是問題... tail -n +15000 outputfilename ...如果您必須使用Node.js那麼這將成爲生成相同輸出文件的已知好方法 –
爲什麼要使用Node.js那?如果只有一個,你可以[使用shell](https://unix.stackexchange.com/questions/37790/how-do-i-delete-the-first-n-lines-of-an-ascii -file-使用殼命令)。 –
這是服務器的日誌文件,所以我認爲服務器每天只保留最新的日誌是很好的,並且清除剩下的日誌文件,而只有一個日誌文件。 – frozen