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 badges
Add a ment  | 

2 Answers 2

Reset to default 6

Look 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