Sarbbottam
Sarbbottam

Reputation: 5570

nodejs - watch directory for changes in background and perform some action

This might be obvious, however I am struggling to find a solution.

// watch.js
var fs = require('fs');

function watch(dir, config) {
  fs.watch(dir, {
    persistent: true,
    recursive: true
  }, (event, filename) => {
    if (filename) {
      console.log(`filename changed: ${filename}`);
      // do something
    }
  });
}

module.exports = watch

I want to run this watch in background, something like nohup, I looked at child_process.spawn but still can't figure out the usage.

As per the documentation child_process.spawn expects a command as the argument.

Any pointer how could I achieve it?

Goal is to watch directory for changes in background and perform some action.

Thanks!

Upvotes: 0

Views: 3331

Answers (1)

KorreyD
KorreyD

Reputation: 1294

if you want to use spawn you can split your watch process into its own script and then spawn it from your main script. then have the main script watch for output.

this is considering your watch function doesn't need to know about anything going on in the calling process.

watcher.js

var fs = require('fs');

function watch(dir, config) {
  fs.watch(dir, {
    persistent: true,
    recursive: true
  }, function(event, filename) {
    if (filename) {
      console.log("filename changed: " + filename); //to stdout
    }
  });
}

watch('./watchme/');  //<- watching the ./watchme/ directory

main.js

const spawn = require('child_process').spawn;
const watch = spawn('node', ['watcher.js']);

watch.stdout.on('data', function(data) {
  console.log("stdout: " + data);
});

watch.stderr.on('data', function(data) {
  console.log("stderr: " + data);
});

watch.on('close', function(code) {
  console.log("child process exited with code " + code);
});

Upvotes: 1

Related Questions