在Chokidar的watcher.on('change)返回空字符串后,Nodejs打印fs.readfile数据

时间:2018-09-07 01:32:25

标签: node.js fs chokidar

每当文件更改时,我都试图读取该文件。文件更改是webpack输出。即使更改后的文件不是空文件,它在返回空字符串时也会产生不一致的结果。我已附上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 个答案:

答案 0 :(得分:1)

问题在于chokidar不会等待文件写入完成,除非它是通过配置定义的。查看chokidar-get-started,最重要的是:

  awaitWriteFinish: {
    stabilityThreshold: 2000,
    pollInterval: 100
  }

此设置应该可以解决您的问题。