node工具之nodemon
原文链接:学习 nodemon 的实现原理
安装依赖
npm i chokidar
创建启动文件
//index.js
const chokidar = require('chokidar'), {spawn} = require('child_process');
//要启动和监听的目标文件
const targetFile = 'main.js'
function debounce(fn, delay) {
var id;
return function() {
clearTimeout(id);
id = setTimeout(function(){
fn()
}, delay)
}
}
var childProcess;
function start() {
childProcess && childProcess.kill();
console.log('start again');
childProcess = spawn('node', [targetFile], {
stdio:[process.stdin, process.stdout, process.stderr]
})
}
chokidar.watch(targetFile).on('all', function(evt, path){
console.log(evt, path);
debounce(start, 500)()
})
创建被监听页面
//main.js
const {createServer} = require('http'), url = require('url')
//创建一个服务器,监听8000端口
createServer(function(req, res){
try {
const pathname = url.parse(req.url).pathname;
console.log('pathname: ', pathname, ['/', '/index'].includes(pathname));
res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8;'});
var resContent = 'index.html'
pathname && ['/', '/index'].includes(pathname) && (resContent = 'hello node')
res.write(resContent)
res.end()
} catch (error) {
console.error(error);
}
}).listen(8000)
console.log(`http server is listening 0.0.0.0:8000`);
效果
小知识
- child_process 子进程
提供了衍生子进程的能力,主要是child_precess.spawn()函数 - child_process.spawn(command[, args][, options])
- chokidar
小而高效的文件监听器