javascript - 如何监视文件并执行查找替换,但不将查找替换捕获为监视文件中的事件

标签 javascript node.js watch

我真的不明白为什么在将“fizbuzz”写入文件 test.txt 时当前会输出两行 - 我知道它正在执行查找和替换,但是有没有办法让查找和替换完成这样的操作它不会被 watch 功能捕获?

const watch = require('node-watch');
const replacer = require('replace-in-file');

const files_to_watch = [
                        '/users/gigatexal/code/nodejs/test.txt',
                        '/users/gigatexal/code/nodejs/test2.txt',
                        '/users/gigatexal/code/nodejs/test3.txt'
                     ] 

设置完成,解决问题

files_to_watch.forEach(f =>
    {
        watch(f, 
            {resursive: false}, 
                function(evt, name){
                    replacer(
                        {
                         files: f, 
                         from: 'fizbuzz', 
                         to: 'foobar'
                        })
                         .then(change=>{console.log('the file ',f,' was fixed.')})
                         .catch(error=>(console.log('oops caught an error', error)));        
                }
            )
    }
);

运行上面的代码:

echo "fizbuzz" >> /users/gigatexal/code/nodejs/test2.txt

输出:

the file  /users/gigatexal/code/nodejs/test.txt  was fixed.
the file  /users/gigatexal/code/nodejs/test.txt  was fixed.

免责声明:我充其量只是一个中级/初学者 python DEV,所以这还不是惯用的 NodeJS 代码。我想了解如何到达那里。

最佳答案

由于您没有提供有关您的操作系统和程序中软件包版本号的太多信息,而且我没有足够的声誉来发表评论。我会尝试提供一些建议,但不太确定它们是否有帮助。

  1. 请务必使用最新版本的 node-watch,v0.5.5。

  2. 创建一个新函数(例如 handle_file)来处理单个文件,以便于调试。

    function handle_file(f) {
      watch(f, function(evt, name) {
        replacer({
          files: f,
          from: 'fizbuzz',
          to: 'foobar'
        })
       .then(change => {
          console.log('the file %s was fixed.', f)
        })
       .catch(error => {
          console.log('oops caught an error', error)
        });
      })
    }
    
    // now only need to do this
    files_to_watch.forEach(handle_file)
    
  3. 用一些日志替换replacer函数,看看是否检测到更改以及是否存在双重更改:

    function handle_file(f) {
      watch(f, function(evt, name) {
        console.log('%s changes.', name);
      })
    }
    
  4. 然后也许您可以知道问题出在哪里。

关于javascript - 如何监视文件并执行查找替换,但不将查找替换捕获为监视文件中的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48017590/

相关文章:

javascript - polymer 双向数据绑定(bind)不起作用

javascript - 模态表单上的 Jquery 验证

javascript - 专注于非输入/ anchor 元素?

node.js - 邮戳模板 : dynamic variable with html processed as text instead of html

node.js - 当文件中有更新时,如何从nodejs中的fs.watch获取更新的数据

php - 提交到多个php脚本

node.js - 如何流式传输到/从 Node 中的文件描述符?

node.js - 如果不更改 sudo 前缀,则无法 npm install -g

gruntjs - grunt watch 检测到文件更改,但不运行任务

javascript - Chrome Devtools 中的 "child"是什么意思?