首页 > 解决方案 > Node WritableStream 不直接级联

问题描述

我正在my.log使用 writestream写入日志文件fs.createWriteStream('my.log', {flags: 'a'})

同时,我还有另一个fs.createReadStream()用于读取my.log文件的代码片段,但是,一旦写入日志文件,这个似乎就没有得到更新。只有当我在我的操作系统(Windows)上手动打开和关闭文件时,它才会被触发。

我该怎么做才能让这个触发器立即发生?我是否每次都重新打开并关闭写入流,例如:

var strm = fs.createWriteStream('my.log', {flags: 'a'})
// log my data
strm.close();
// rinse and repeat

标签: javascriptnode.jsstreamfilesystems

解决方案


看来这归结为 Node/Windows 中的一个问题:

  • “fs.watch API 并非 100% 跨平台一致,在某些情况下不可用”
  • “在 Windows 系统上,此功能取决于 ReadDirectoryChangesW。”

https://nodejs.org/api/fs.html#fs_availability

因此,作为解决方案,我现在使用:

// https://www.npmjs.com/package/tail
var Tail = require('tail').Tail;
// Pass property to force the usage of fs.watchFile
tail = new Tail('my.log', { useWatchFile: true });

如果您不想使用包“tail”,那么您应该手动使用fs.watchFile并对文件更改采取相应措施。


推荐阅读