node.js monitoring for when a file is created

file-io, fs, javascript, node.js

Solution

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.

Problem

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?

Original source