MYV
MYV

Reputation: 4534

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?

Upvotes: 4

Views: 4295

Answers (2)

Farid Nouri Neshat
Farid Nouri Neshat

Reputation: 30410

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.

Upvotes: 2

Joe
Joe

Reputation: 42577

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.

Upvotes: 6

Related Questions