NodeJS fs.watch 没有对 Docker 容器内的变化做出反应

NodeJS fs.watch is not reacting to changes inside a Docker Container

以下代码的想法是对文件夹内文件的更改做出反应。当我在我的 macOS 上 运行 这段代码时,一切正常。

let fs = require("fs");

let options = {
    encoding: 'buffer'
}

fs.watch('.', options, function(eventType, filename) {

    if(filename)
    {
        console.log(filename.toString());
    }

});

另一方面,在 Docker 容器中,代码不会对文件更改做出反应。我运行代码如下:

docker run -it --rm --name $(basename $(pwd)) -v $(pwd):/app -w /app node:slim sh -c 'node index'

是否有与 Docker 一起使用以允许系统通知文件更改的选项?

新答案

最初我建议 Gulp(请参阅更新后 post 的底部和旧答案)。它没有工作,因为你试图以编程方式使用它,当 Gulp 是任务 运行ner 并且有自己的使用模式时,我没有描述。由于您需要特定的东西,我为您提供了非常简单、可靠的解决方案。

它使用了 gulp 使用的模块之一,称为 gaze - 每周约有 170 万次下载的模块。它的工作,肯定在每个系统上。

npm install gaze --save

为了让它工作,让我们在您的根文件夹中创建 index.js(它将安装到 docker 内的 app 文件夹,然后只需按照中给出的基本说明进行操作模块自述文件:

 var gaze = require('gaze');

 // Watch all .js files/dirs in process.cwd() 
 gaze('**/*.js', function(err, watcher) {
 // Files have all started watching 
 // watcher === this 
 console.log('Watching files...');

 // Get all watched files 
 var watched = this.watched();

 // On file changed 
 this.on('changed', function(filepath) {
  console.log(filepath + ' was changed');
 });

 // On file added 
 this.on('added', function(filepath) {
   console.log(filepath + ' was added');
 });

  // On file deleted 
 this.on('deleted', function(filepath) {
  console.log(filepath + ' was deleted');
 });

 // On changed/added/deleted 
 this.on('all', function(event, filepath) {
  console.log(filepath + ' was ' + event);
 });

  // Get watched files with relative paths 
   var files = this.relative();
  });

现在让运行你的命令:

docker run -it --rm --name $(basename $(pwd)) -v $(pwd):/app -w /app node sh -c 'node index'

我们有什么变化 - Linux 输出,但这也适用于 Mac OS。

   blackstork@linux-uksg:~/WebstormProjects/SO/case1> docker run -it --rm --name $(basename $(pwd)) -v $(pwd):/app -w /app node sh -c 'node index'
   Watching files...
   /app/bla was changed
   /app/foobar.js was changed

旧答案。

You can do it with gulp. Gulpfile.js

 const gulp = require('gulp');

 gulp.task( 'watch' , ()=>{
    return gulp.watch(['app/**'], ['doStuff']);
 });

 gulp.task( 'doStuff', cb => {
   console.log('stuff');
   //do stuff
   cb();
  });

So far such approach worked for me (of course you can build much more complex things, but if find using gulp conventient for different filesystem tasks).