admin管理员组文章数量:1335664
I am writing a node.js program that needs to do something as soon as a file with a certain name is created in a specific directory. I could do this by doing repeated calls to fs.readdir until I see the name of the file, but I'd rather do something more efficient. Does anyone know of a way to do this?
I am writing a node.js program that needs to do something as soon as a file with a certain name is created in a specific directory. I could do this by doing repeated calls to fs.readdir until I see the name of the file, but I'd rather do something more efficient. Does anyone know of a way to do this?
Share edited May 18, 2014 at 3:56 Manquer 7,6478 gold badges45 silver badges71 bronze badges asked May 18, 2014 at 3:28 MYVMYV 4,5547 gold badges29 silver badges24 bronze badges2 Answers
Reset to default 6Look at the fs.watch
(and fs.watchFile as a fallback) implementation, but realize it is not perfect:
http://nodejs/api/fs.html#fs_fs_watch_filename_options_listener
Caveats#
The fs.watch API is not 100% consistent across platforms, and is unavailable in some situations. Availability#
This feature depends on the underlying operating system providing a way to be notified of filesystem changes.
On Linux systems, this uses inotify. On BSD systems (including OS X), this uses kqueue. On SunOS systems (including Solaris and SmartOS), this uses event ports. On Windows systems, this feature depends on ReadDirectoryChangesW.
If the underlying functionality is not available for some reason, then fs.watch will not be able to function. For example, watching files or directories on network file systems (NFS, SMB, etc.) often doesn't work reliably or at all.
You can still use fs.watchFile, which uses stat polling, but it is slower and less reliable.
You basically can use fs.watchFile
or fs.watch
yourself or use a node module to does it for you, which I strongly remend to use a node module.. To non-buggy cross-platform and fast solution, it might be tricky. I suggest to use chokidar or have a look at other modules that does this.
With chokidar you can do this:
var chokidar = require('chokidar');
var watcher = chokidar.watch('YourDirecrtory');
watcher.on('add', function(path) {console.log('File', path, 'has been added');});
Then you wouldn't have to care about edge cases or cross platform support.
本文标签: javascriptnodejs monitoring for when a file is createdStack Overflow
版权声明:本文标题:javascript - node.js monitoring for when a file is created - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742266579a2443511.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论