只读取文件中的附加内容
Only reading additional content in a file
我正在做一个需要读取日志文件的项目,日志文件可能会变得很大,所以我只想读取添加到文件中的额外数据而不是旧数据以避免潜在的性能问题。
我试过 fs.createReadStream 但它似乎没有用:
代码:
let stream = fs.createReadStream(`/path/`, { autoClose: true, encoding: "utf-8" });
stream.on('ready', () => {
console.log("Loaded log file!");
})
stream.on("data", chunk => {
// Data stream
});
stream.on("end", () => {
stream.pause();
console.log("ended");
// Going thru the data
setTimeout(() => {
stream.resume();
stream.read();
}, 10000);
});
使用该代码,“结束”事件仅触发一次,尽管流设置为不自动关闭,并且没有其他数据通过。
在对 readStream 进行了一些处理之后,感谢@KyleRifqi,我能够想出这个解决方案,存储最后的字节数并在每次流结束时更新它。
let lastBytes = 0;
let text = "";
let stream = fs.createReadStream(`/path/`, { autoClose: true, encoding: "utf-8", start: lastBytes });
stream.on('ready', () => {
console.log("Loaded log file!");
});
stream.on("data", chunk => {
text += chunk;
});
stream.on("end", () => {
let read = Buffer.byteLength(text, "utf-8");
lastBytes += read;
//Code here
});
我正在做一个需要读取日志文件的项目,日志文件可能会变得很大,所以我只想读取添加到文件中的额外数据而不是旧数据以避免潜在的性能问题。
我试过 fs.createReadStream 但它似乎没有用:
代码:
let stream = fs.createReadStream(`/path/`, { autoClose: true, encoding: "utf-8" });
stream.on('ready', () => {
console.log("Loaded log file!");
})
stream.on("data", chunk => {
// Data stream
});
stream.on("end", () => {
stream.pause();
console.log("ended");
// Going thru the data
setTimeout(() => {
stream.resume();
stream.read();
}, 10000);
});
使用该代码,“结束”事件仅触发一次,尽管流设置为不自动关闭,并且没有其他数据通过。
在对 readStream 进行了一些处理之后,感谢@KyleRifqi,我能够想出这个解决方案,存储最后的字节数并在每次流结束时更新它。
let lastBytes = 0;
let text = "";
let stream = fs.createReadStream(`/path/`, { autoClose: true, encoding: "utf-8", start: lastBytes });
stream.on('ready', () => {
console.log("Loaded log file!");
});
stream.on("data", chunk => {
text += chunk;
});
stream.on("end", () => {
let read = Buffer.byteLength(text, "utf-8");
lastBytes += read;
//Code here
});