【问题标题】:Make the sails.js server monitor file change using chokidar and then emit socket message使用 chokidar 使sails.js 服务器监控文件更改,然后发出套接字消息
【发布时间】:2014-07-15 11:24:57
【问题描述】:

我使用 chokidar 来监控文件夹中的文件是否已更改。目前,当用户在我的 ExperimentController 中更新 Experiment Model 时会触发它。

var chokidar = require('chokidar');
...
var watcher = chokidar.watch('assets/output-model-files', {ignored: /[\/\\]\./, persistent: true});
watcher.on('change', function(path) {
...read my changed file and update the content of my database, and send a socket publishUpdate message...
... read file content in an asynchronous way
fs.readFile(path,"utf-8", function (err, data) {
... update the experiment object with the content of the changed file
Experiment.update(req.param('id'), ExpObj, function expUpdated(err) {});
... send a message via socket saying that the exeriment object has been updated             
Experiment.publishUpdate(req.param('id'), {name: exp.name,
    results: JSON.stringify(myres),
    action: ('file has just been updated. nb of trajectories: '+totalNbTrajectories)
});

但我想持续监控目标文件夹中的任何更改,并在sails.js 服务器启动时发送 Experiment.publishUpdate 消息,而不是在用户更新实验对象时发送。 我可以在哪里将该 chokidar.watch(...) 代码放在服务器端,以便从文件更改中更新实验对象? socket.js?

【问题讨论】:

    标签: sockets sails.js


    【解决方案1】:

    好的。我发现在 bootstrap.js 中定位代码似乎可以完美地重新调整偶数触发...

    我的 bootstrap.js 现在看起来像:

    var chokidar = require('chokidar');
    var fs = require('fs');
    var os = require('os');
    var sys = require('sys');
    module.exports.bootstrap = function(cb) {
    
    // It's very important to trigger this callack method when you are finished 
    // with the bootstrap!  (otherwise your server will never lift, since it's waiting on the bootstrap)
    
      User.update({}, {online: false},
        function userUpdated(err, users) {
            if (err) {
                console.log(err);
            } else {
                var watcher = chokidar.watch('assets/output-model-files', {ignored: /[\/\\]\./, persistent: true});
                watcher.on('change', function(path) {
                            console.log('File', path, 'has been changed'); 
                            // do file reading and presumably Experiment publish update here
                });
            }
    
            cb();
        }
      )
    
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      • 2019-03-15
      • 2014-08-12
      • 2015-01-09
      • 2015-06-21
      相关资源
      最近更新 更多