‘wx+’ – 与 ‘w+’ 相似,但如果路径已存在则失败。
fs.Stats 类
fs.Stats 对象提供有关文件的信息。
Stats {
dev: 2114,
ino: 48064969,
mode: 33188,
nlink: 1,
uid: 85,
gid: 100,
rdev: 0,
size: 527,
blksize: 4096,
blocks: 8,
atimeMs: 1318289051000.1,
mtimeMs: 1318289051000.1,
ctimeMs: 1318289051000.1,
birthtimeMs: 1318289051000.1,
atime: Mon, 10 Oct 2011 23:24:11 GMT,
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
birthtime: Mon, 10 Oct 2011 23:24:11 GMT } 开始监听日志文件
前提,在app.js中调用watchFile方法,将需要监听的文件路径传入该方法中。
function watchFile(filename) {
console.log('Log monitoring...');
// Open the file for reading and appending
fs.open(filename, 'a+', function (err, fd) {
if (err) {
throw err;
}
var buffer;
fs.watchFile(filename, {
persistent: true,
interval: 1000
}, (curr, prev) => {
// Compare the time before and after
if (curr.mtime > prev.mtime) {
// console.log(`The current latest revision time is: ${curr.mtime}`);
// console.log(`The latest modification time is: ${prev.mtime}`); // Changes in the contents of documents
buffer = new Buffer(curr.size - prev.size);
// (curr.size - prev.size) this is the newly added length of the log file
readFile(fd, buffer, (curr.size - prev.size), prev.size);
}
});
});
}
读取新增内容
function readFile(fd, buffer, length, position) {
// read file
fs.read(fd, buffer, 0, length, position, function (err, bytesRead, buffer) {
if (err) {
log.error(err);
}
console.log('Additional Contents', buffer.toString());
});
}额外功能:读取历史内容
function fetchHistoryLogs(filename) {
const rl = readLine.createInterface({
input: fs.createReadStream(filename, {
enconding: 'utf8'
}),
output: null,
terminal: false
}); rl.on('line', (line) => {
if (line) {
logsArr.push(line.toString());
}
}).on('close', () => {
for (var i = 0; i < logsArr.length; i++) {
// Print the data for each row
console.log(`Original data: n ${logsArr[i]}`);
}
});
}
总结
以上所述是小编给大家介绍的Nodejs监听日志文件的变化的过程解析,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!









