nodejs:primefaces文件replace操作,只触发一次观察者一次
我有两种过程。 一个人应该写一个文件,其他人应该读它,如果它被改变。
我发现fs.watch
得到读取过程通知,如果他们必须重新加载文件。
要写文件,我可以使用fs.writeFile
。
但是我不确定,如果这是一个primefacesreplace。 如果文件很大,会多次触发watch
?
将这个作为primefaces操作,正确的方法是什么?
仅供参考:在目标系统上运行Linux。
经过一些testing,我得到了这个结果:
大文件写入时, fs.watch
会多次触发change
事件。 问题是,你不能看到,这是最后一个弄清楚,写操作已经完成。
解决方法是:在同一个目录中写入一个临时文件,然后使用link
和unlink
来replace旧文件。
在代码中,它可能看起来像这样:
var fs = require("fs"); var path = require("path"); var consts = require('constants'); /** * write given date in temp file and replace the dstpath with that. * * @author Tobias Lindig * * @param {string} dstpath destination path * @param {string} data [description] * * @throws {Error} If fs operations failed. */ function atomicWrite(dstpath, data) { // build a unique temp path var dir = path.dirname(dstpath); var tempName = [ 'temp', process.pid, (Math.random() * 0x1000000000).toString(36), new Date().getTime() ].join('-'); var tempPath = path.join(dir, tempName); var tempOptions = { encoding: 'utf8', mode: 420, // aka 0644 in Octal flags: consts.O_CREAT | consts.O_TRUNC | consts.O_RDWR | consts.O_EXCL }; //local function to remove temp file var fn_removeTempFileSync = function() { try { fs.unlinkSync(tempPath); } catch (ex) { // ignore fail, may be file was not created. } }; try { fs.writeFileSync(tempPath, data, tempOptions); // remove possible old version of file // because fs.link can not overwrite existing dstpath. if (fs.existsSync(dstpath)) { fs.unlinkSync(dstpath); } //copy temp file to destination path fs.linkSync(tempPath, dstpath); fn_removeTempFileSync(); } catch (ex) { fn_removeTempFileSync(); throw ex; } }
现在fs.watch
激活文件(“dstpath”)的事件change
一次。
这个理论。
但是在现实世界中,不幸的是, change
事件并没有被触发,有的时候它错过了。 所以我也看重rename
事件。
该事件将按此顺序进行:
rename
//永远,如果文件被删除rename
//永远,文件被创buildchange
有时,文件被创build
为了只读一次文件,我认为文件的mtime
是只读的,如果不一样的话。