AhmetEnesKCC
AhmetEnesKCC

Reputation: 89

Watch files and folders recursively with node js ( Also get info whenever changes )

I want to watch files and folders whenever they change in a specific directory. fs.watch is doing good but not giving enough information about which file or folder changed. What must I use to get detailed information when watching files.

Upvotes: 1

Views: 5209

Answers (2)

Nom
Nom

Reputation: 373

I just want to add for anyone reading this in 2022 - file.watch now works recursively on Linux as of Node.js v20.

Upvotes: 7

O. Jones
O. Jones

Reputation: 108696

I guess you use the fs.watch() function to do this. It works somewhat differently on different OSs. Only on Windows and MacOS does the { recursive: true } option work. On other OSs (and indeed on all OSs if you are writing portable code) you have to watch all the subdirectories you want as well.

As you know it works like this. Once you know the filename you can use fs.stat() to learn more about the file from the Stats object. (This sample code is not debugged)

fs.watch('whatever/directory/name', { }, (eventType, filename) => {
  if (eventType === 'change') {
    fs.stat (filename, function (err, stat) {
      if(err) return console.error(err)
      const modTime = stat.mtimeMs
      const size = stat.size
      if (stat.isFile()) {
        /* this is an ordinary file */
      }
    } )
});

If fs.stat() doesn't give you enough information, you may have to read the file itself to figure things out.

Upvotes: 5

Related Questions