javascript - 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
解决方案
看来这归结为 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
并对文件更改采取相应措施。
推荐阅读
- node.js - 如何使用 NodeJS 登录 Azure AD?
- python - 比较两个文件以打印与单词匹配的行
- performance - 从源代码/从头开始编译 linux perf 工具及其依赖的内核模块
- javascript - 加载图像不是矩形
- line - 边界梯形/线间隔
- javascript - 未定义不是反应原生的对象
- spring-boot - Springboot 2 RESTful 应用程序使用 Procfile 部署到 heroku
- google-sheets - 谷歌电子表格计数除某些值以外的非空单元格
- java - 如何将文件读入以列表为值的哈希图中?
- python-3.x - pandas 逗号分隔层次结构 groupby sum