The Node service started by Nodemon restarts the server after detecting changes in the target file

  • Listen for changes in the object file
  • Restart server -> Stop Server + Start server

1. Listen for file changes

Nodejs own fs. Watch | | fs. WatchFile changes can be done to monitor files, system compatibility and other small problems but, here it is recommended to use chokidar listening in to deal with file

🔗 chokidar

const chokidar = require('chokidar');

chokidar.watch(['index.js']).on('all'.(event, path) = > {
  console.log(event, path);
});
Copy the code

2. Restart the server

Restarting the server is divided into closing the server and restarting the server, and processing after listening for file changes

const chokidar = require('chokidar');
const { spawn } = require('child_process')

const start = debounce(restart, 500);

let childProcess = null;
chokidar.watch(['index.js']).on('all'.(event, path) = > {
  console.log(event, path)
  start();
});

function restart() {
  // Kill the previous process before restarting the server
  childProcess && childProcess.kill();
  childProcess = spawn('node'['index.js'] and {stdio: [process.stdin, process.stdout, process.stderr]
  })
}

function debounce(f, delay) {
  let timer = null;
  return function() {
    timer && clearTimeout(timer);
    timer = setTimeout(() = >{ f(); }, delay); }}Copy the code

🔗 github.com/xuyede/node…