Nodejs Printing fs.readfile data after chokidar's watcher.on('change) returns an empty string

Viewed 813

I am trying to read the file whenever it changes. The file change is a webpack output. It is giving inconsistent results where it is returning an empty string even when the changed file is not emtpy. I have attached the screenshot of the logs.

var watcher = chokidar.watch(path.resolve(__dirname, '../../dist/main.root.js'), /^\./, {persistent : true, usePolling: true, interval: 1000})

watcher
 .on('add', path => {
    // fileAdded(path)
    console.log(`File ${path} has been added`, Date.now())
  })
  .on('change', path => {
    console.log(`File ${path} has been changed`)
    fileChanged(path)
  })

function fileChanged (path) {
  fs.readFile(path, 'utf8', (err, data) => {
    if (err) {
      console.error(err)
    } else {
      var target = data
      console.log('***target***', typeof target, target)
      console.log('***path***', path)
    }
  })
}
1 Answers

The problem is that chokidar is not waiting for the file write finish unless it is defined through configuration. Check out chokidar-get-started and most importantly:

  awaitWriteFinish: {
    stabilityThreshold: 2000,
    pollInterval: 100
  }

This setting should solve your issue.

Related