Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watch a folder for changes using node.js, and print file paths when they are changed

Tags:

node.js

I'm trying to write a node.js script that watches for changes in a directory of files, and then prints the files that are changed. How can I modify this script so that it watches a directory (instead of an individual file), and prints the names of the files in the directory as they are changed?

var fs = require('fs'),     sys = require('sys'); var file = '/home/anderson/Desktop/fractal.png'; //this watches a file, but I want to watch a directory instead fs.watchFile(file, function(curr, prev) {     alert("File was modified."); //is there some way to print the names of the files in the directory as they are modified? }); 
like image 470
Anderson Green Avatar asked Dec 04 '12 02:12

Anderson Green


People also ask

How do you view file changes in node JS?

To watch any changes that are made to the file system, we can use the fs module provided by node. js that provides a solution here. For monitoring a file of any modification, we can either use the fs. watch() or fs.

How do I find the path of a file in node?

To check the path in synchronous mode in fs module, we can use statSync() method. The fs. statSync(path) method returns the instance of fs. Stats which is assigned to variable stats.

Which command is used to print the current working directory in node JS?

The process. cwd() function returns the current working directory of the Node.


1 Answers

Try Chokidar:

var chokidar = require('chokidar');  var watcher = chokidar.watch('file or dir', {ignored: /^\./, persistent: true});  watcher   .on('add', function(path) {console.log('File', path, 'has been added');})   .on('change', function(path) {console.log('File', path, 'has been changed');})   .on('unlink', function(path) {console.log('File', path, 'has been removed');})   .on('error', function(error) {console.error('Error happened', error);}) 

Chokidar solves some of the crossplatform issues with watching files using just fs.

like image 103
mtsr Avatar answered Sep 21 '22 13:09

mtsr