静态版本:监听的文件名写死了
// 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...`);