Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js monitoring for when a file is created

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?

like image 586
MYV Avatar asked Sep 12 '25 11:09

MYV


2 Answers

Look at the fs.watch (and fs.watchFile as a fallback) implementation, but realize it is not perfect:

http://nodejs.org/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.

like image 165
Joe Avatar answered Sep 14 '25 02:09

Joe


You basically can use fs.watchFile or fs.watch yourself or use a node module to does it for you, which I strongly recommend 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.

like image 41
Farid Nouri Neshat Avatar answered Sep 14 '25 02:09

Farid Nouri Neshat