3

每当文件更改时,我都会尝试读取文件。文件更改是 webpack 输出。即使更改的文件不是空的,它也会在返回空字符串的情况下给出不一致的结果。我附上了日志的截图

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

1 回答 1

4

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

  awaitWriteFinish: {
    stabilityThreshold: 2000,
    pollInterval: 100
  }

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

于 2018-10-14T13:56:46.630 回答