How to let chokidar watcher keep running in the background in electron JS/ Node JS

1.1k views Asked by At

I am using chokidar library for keeping track of files. So I created this function:

function StartWatcher(username){
    console.log(username)
    const chokidar = require('chokidar');
    const folderLocation='watch-folder'

    const watcher = chokidar.watch(folderLocation,{
        persistent: false,
        ignoreInitial: true,
        ignored: [ 'watch-folder/ignore-1.txt', 'watch-folder/ignore-2.txt' ],
        ignorePermissionErrors: false,
        interval: 100,
        binaryInterval: 300,
        disableGlobbing: false,
        enableBinaryInterval: true,
        useFsEvents: false,
        usePolling: false,
        atomic: true,
        followSymlinks: true,
        awaitWriteFinish: false
    })
    
    watcher.on('ready',async()=>{
        console.log("I am ready to watch files for ",username)
        console.log(folderLocation)
    })

    watcher.on('add',async (path) => {
        console.log(path,'File Path ....... for',username)
        var today = new Date();
        var fileAddingDate=today.getDate()+"/"+(today.getMonth()+1)+"/"+today.getFullYear()+" "+today.getHours()+":"+today.getMinutes()+":"+today.getSeconds()
        fs.readFile(path,async function(error,data){
            console.log(data)
        })
    })

    watcher.on('change',async (path)=>{
        console.log(path,'Content change in the file... for',username);
        var today = new Date();
        var fileAddingDate=today.getDate()+"/"+(today.getMonth()+1)+"/"+today.getFullYear()+" "+today.getHours()+":"+today.getMinutes()+":"+today.getSeconds()
        fs.readFile(path,async function(error,data){
          console.log(data)
        })
    })
}

And now I am calling this function on some condition like this.

StartWatcher(devansh)

But I am having problem. Only ready event is working. Rest all events are not working. I thinks it's because when I am calling the function it got executed only once and stopped. Need some help.

1

There are 1 answers

0
Juan Mallet On

I don't know if you found a solution to this problem yet but, looking at your function and what is happening to you, your problem is that you setted "persistent" as "false", which causes no more events to be emitted after "ready" event as you can check in it's API: https://www.npmjs.com/package/chokidar#user-content-persistence