Search code examples
javascriptnode.jswatch

How to watch file(s) and perform find-replace but not capture that find-replace as an event in watched file


I do not really understand why this currently outputs two lines when writing say 'fizbuzz' to file test.txt -- I know it is doing find and replace but is there a way to get the find and replace to be done such that it does not get caught by the watch function?

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'
                     ] 

setup done, on to the problem

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

With the above running:

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

Outputs:

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

disclaimer: I am only an intermediate/beginner python DEV at best so this isn't idiomatic NodeJS code, not yet. I want to learn how to get it there.


Solution

  • Since you didn't provide much information about your OS and versions number of the packages in the program, and I don't have enough reputation to comment. I'll try to give some suggestions instead but not quite sure if they would help.

    1. Make sure to use the latest version of node-watch, v0.5.5 by now.

    2. Create a new function (say handle_file) to handle on a single file, so that's easy to debug.

      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. Replace the replacer function with some logs to see if the changes are detected and if there are double changes:

      function handle_file(f) {
        watch(f, function(evt, name) {
          console.log('%s changes.', name);
        })
      }
      
    4. And then maybe you can tell where the problems are located.