Open dounai1306 opened 5 years ago
小伙伴配置了mock的watch后,我本地使用npm run mock:watch 出现如题的报错信息,google后发现是因为npm在不同运行平台下的执行名不一样。 server = spawn(process.platform === "win32" ? "npm.cmd" : "npm", ['run', 'mock']);
npm run mock:watch
server = spawn(process.platform === "win32" ? "npm.cmd" : "npm", ['run', 'mock']);
const chokidar = require('chokidar'); const { spawn } = require('child_process'); const path = require('path'); const log = console.log.bind(console); const children = []; let server; function restart() { if (server) { server.kill(); } server = spawn(process.platform === "win32" ? "npm.cmd" : "npm", ['run', 'mock']); children.push(server); server.on('exit', function() { log('JSON Server is closed'); log('JSON Server is restarting'); }); server.on('error', function(err) { log('error: ' + err); }); server.stdout.on('data', function(data) { log(data.toString()); }); } const watcher = chokidar.watch(path.resolve(__dirname, './'), { ignored: /watch.js/, recursive: true, persistent: true }); watcher .on('add', path => { log(`File ${path} has been added`); }) .on('change', path => { log(`File ${path} has been changed`); restart(); }) .on('unlink', path => { log(`File ${path} has been removed`); restart(); }); process.on('exit', function() { log('process is exited'); children.forEach(function(child) { child.kill(); }); }); restart();
上面这段代码其实执行得是一个文件监听,对于文件的新增、修改、删除做实时监听然后进行重启服务,在前段开发过程中需要对mock的一些数据做实时调整的时候,这段代码就会减少我们人肉关闭服务重启服务的操作了。
核心是依赖chokidar这个库对文件进行一个监听,虽然node自身也有相关的方法来实现文件监听,但是不能进行一个递归监控。
小伙伴配置了mock的watch后,我本地使用
npm run mock:watch
出现如题的报错信息,google后发现是因为npm在不同运行平台下的执行名不一样。server = spawn(process.platform === "win32" ? "npm.cmd" : "npm", ['run', 'mock']);