Question

I would like to track new files in a directory. I used the script given in the documentation: http://nodejs.org/api/fs.html#fs_fs_watch_filename_options_listener

var fs = require('fs');
fs.watch('mydir/', function (event, filename) {
    console.log('event is: ' + event);
    if (filename) {
        console.log('filename provided: ' + filename);
    } else {
        console.log('filename not provided');
    }
});

And I added files to mydir/ using touch hello.txt for example.

When running the script, I don't get the new file name, because the emitted event is rename!! Here is the console output.

event is: rename
filename not provided

How can I get the file new name hello.txt?

Thanks.

Was it helpful?

Solution

The same page also describes your issue:

Providing filename argument in the callback is not supported on every platform (currently it's only supported on Linux and Windows). Even on supported platforms filename is not always guaranteed to be provided.

I think your best bet is to switch to another module providing similar functionality, like watch (which I don't have any experience with myself).

OTHER TIPS

fs.watch('somedir', (event, filename) => {
})

The filename here works, all you need is to track the second parameter.

Mac 10.11.3, Node v5.9

chokidar at https://github.com/paulmillr/chokidar was easy to setup. Follow the instructions in the README to setup. Here's a quick example I used to detect when a video file was generated in a /video subfolder relative to the root of my Node.js app:

  • Install Node.js (includes NPM)
  • Generate package.json npm init
  • Install Chokidar library into /node_modules subfolder and save the dependency to package.json npm install chokidar --save
  • Create an example program file (i.e. touch video.js)
  • Create a folder to watch (i.e. mkdir videos)
  • Add the following code to video.js (as described in the README, which will watch for changes in the /videos subfolder and ignore filenames prefixed with a full stop): var chokidar = require('chokidar'); chokidar.watch('./videos', {ignored: /[\/\\]\./}).on('all', function(event, path) { console.log(event, path); });

  • Start the program node video.js that prints to output indicating that the /videos subdirectory and its contents are being watched, i.e. $ node video.js addDir ./videos

  • Copying/Saving a file (i.e. test.mov) into the /videos subdirectory prints the following to standard output in terminal: add videos/test.mov
  • Removing the file prints the following to terminal: unlink videos/test.mov
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top