靜態版本:監聽的文件名寫死了
// watcher.js
'use strict'
const fs = require('fs');
fs.watch('target.txt', () => console.log('File changed!'));
console.log('Now watching target.txt for changes...');
node watcher.js
動態版本:在命令行輸入需要監聽的文件名.
// watcher-argv.js
'use strict'
const fs = require('fs');
console.log(process.argv);
const filename = process.argv[2];
if (!filename) {throw Error('A file to watch must be specified!');
}
fs.watch(filename, () => { console.log(`File ${filename} changed!`));
console.log(`Now watching ${filename} for changes...`);

使用子進程對變化文件進行操作
- 在開發中最常見的做法是把不同的工作放在不同的獨立進程中執行
- 在監聽到文件變化后,創建一個子進程,再用這個子進程執行系統命令
- child-process模塊是node.js中的子進程模塊
// watcher-spawn.js
'use strict';
const fs = require('fs');
const spawn = require('child_process').spawn;
const filename = process.argv[2];if (!filename) {throw Error('A file to watch must be specified!');
}fs.watch(filename, () => {const ls = spawn('ls', ['-l', '-h', filename]);ls.stdout.pipe(process.stdout);
});
console.log(`Now watching ${filename} for changes...`);