【问题标题】:nodejs - watch directory for changes in background and perform some actionnodejs - 在后台监视目录并执行一些操作
【发布时间】:2016-04-13 06:41:44
【问题描述】:

这可能很明显,但我正在努力寻找解决方案。

// 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

我想在后台运行这个watch,类似于nohup,我查看了child_process.spawn,但仍然无法弄清楚它的用法。

根据文档,child_process.spawn 期望 command 作为参数。

任何指针我该如何实现它?

目标是在后台监视目录的变化并执行一些操作。

谢谢!

【问题讨论】:

  • “在后台”是什么意思? Node.js 是异步的;听起来您只想调用该函数。
  • 类似于nohup 我希望运行binary 它将在终端中返回提示并继续监视文件系统。
  • 然后你需要用命令行运行一个新进程。 (可能是node somefile.js
  • 目标是监视目录的背景变化并执行一些操作。 - 有什么例子吗?
  • 为什么要这么做,fs.watch不是已经异步了,在事件循环中只处理回调吗?

标签: node.js background-process watch spawn


【解决方案1】:

如果你想使用 spawn,你可以将你的 watch 进程拆分为它自己的脚本,然后从你的主脚本中生成它。然后让主脚本监视输出。

这是考虑到您的 watch 函数不需要知道调用过程中发生的任何事情。

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);
});

【讨论】:

  • 如何让主进程完成,我试过options = { detached :true, stdio: ['ignore'] } & watch.unref()
  • 哦,好吧,所以你只想使用 main 来启动其他脚本。作为数组的 stdio 选项实际上有 3 个元素,它们分别是 stdin、stdout、stderr。所以你应该像这样忽略所有 3 个:{ detached :true, stdio: ['ignore','ignore','ignore'] }。您也可以只使用字符串作为 stdio 选项值,这将适用于所有 3 个,因此:{ detached :true, stdio: 'ignore' } 将做同样的事情
  • 如果你忽略,那么 stdout.on 和 stderr.on 处理程序会抛出一个错误,所以如果使用 stdio: 'ignore' ,你需要删除它们
  • 这样做有什么好处?反正 fs.watch 不是已经异步了,只有回调在单线程中运行吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-12
  • 1970-01-01
  • 2012-08-30
  • 1970-01-01
  • 2020-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多