Watching a file or directory for changes is an important part of automation. We all enjoy using our favorite CSS preprocessor's "watch" feature -- we can still refresh the page and see our changes as though we were simply writing in pure CSS. Node.js makes both file and directory watching easy -- but it's a bit more difficult than you may think.
监视文件或目录中的更改是自动化的重要部分。 我们都喜欢使用我们最喜欢CSS预处理器的“监视”功能-我们仍然可以刷新页面并看到所做的更改,就好像我们只是在用纯CSS编写一样。 Node.js使文件和目录的监视变得容易-但比您想象的要困难一些。
Simply put: Node.js' watching features aren't consistent or performant yet, which the documentation admits. The good news: a utility called chokidar stabilizes file watching and provides added insight into what has happened. chokidar provides a wealth of listeners; instead of providing boring reduced examples, here's what chokidar provides you:
简而言之: 文档承认 ,Node.js的监视功能还不一致或尚未实现。 好消息:名为chokidar的实用程序可稳定文件监视,并提供更多有关已发生事件的信息。 chokidar提供了大量的听众; 与其提供无聊的简化示例,不如这是chokidar为您提供的:
var chokidar = require('chokidar'); var watcher = chokidar.watch('file, dir, or glob', { ignored: /[\/\\]\./, persistent: true }); var log = console.log.bind(console); watcher .on('add', function(path) { log('File', path, 'has been added'); }) .on('addDir', function(path) { log('Directory', path, 'has been added'); }) .on('change', function(path) { log('File', path, 'has been changed'); }) .on('unlink', function(path) { log('File', path, 'has been removed'); }) .on('unlinkDir', function(path) { log('Directory', path, 'has been removed'); }) .on('error', function(error) { log('Error happened', error); }) .on('ready', function() { log('Initial scan complete. Ready for changes.'); }) .on('raw', function(event, path, details) { log('Raw event info:', event, path, details); }) // 'add', 'addDir' and 'change' events also receive stat() results as second // argument when available: http://nodejs.org/api/fs.html#fs_class_fs_stats watcher.on('change', function(path, stats) { if (stats) console.log('File', path, 'changed size to', stats.size); }); // Watch new files. watcher.add('new-file'); watcher.add(['new-file-2', 'new-file-3', '**/other-file*']); // Un-watch some files. watcher.unwatch('new-file*'); // Only needed if watching is `persistent: true`. watcher.close(); // One-liner require('chokidar').watch('.', {ignored: /[\/\\]\./}).on('all', function(event, path) { console.log(event, path); });What a wealth of handles, especially when you've experienced the perils of `fs` watch functionality. File watching is essential to seamless development and chokidar makes life easy!
丰富的处理能力,尤其是当您经历过`fs'手表功能的危险时。 观察文件对于无缝开发至关重要,chokidar使生活变得轻松!
翻译自: https://davidwalsh.name/node-watch-file