我试图使用以下代码监视与node.js'watchFile()(软)符号链接的文件:
var fs=require('fs')
, file= './somesymlink'
, config= {persist:true, interval:1};
fs.watchFile(file, config, function(curr, prev) {
if((curr.mtime+'')!=(prev.mtime+'')) {
console.log( file+' changed');
}
});
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,./ somesymlink是/ path/to///file的(软)符号链接.当对/ path/to////文件进行更改时,不会触发任何事件.我必须用/ path/to//// file替换符号链接才能使它工作.在我看来,watchFile无法观看符号链接的文件.当然我可以通过使用spawn + tail方法来完成这项工作,但我不想使用该路径,因为它会引入更多开销.
所以我的问题是如何使用watchFile()在node.js中观看符号链接文件.提前谢谢大家.
Lin*_*iel 24
你可以使用fs.readlink:
fs.readlink(file, function(err, realFile) {
if(!err) {
fs.watch(realFile, ... );
}
});
Run Code Online (Sandbox Code Playgroud)
当然,你可以变得更加漂亮,并编写一个可以观察文件或链接的小包装器,因此您不必考虑它.
更新:这是一个未来的包装器:
/** Helper for watchFile, also handling symlinks */
function watchFile(path, callback) {
// Check if it's a link
fs.lstat(path, function(err, stats) {
if(err) {
// Handle errors
return callback(err);
} else if(stats.isSymbolicLink()) {
// Read symlink
fs.readlink(path, function(err, realPath) {
// Handle errors
if(err) return callback(err);
// Watch the real file
fs.watch(realPath, callback);
});
} else {
// It's not a symlink, just watch it
fs.watch(path, callback);
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2753 次 |
| 最近记录: |