Restart a Node.js Server

First, start a server

const server = http.createServer(...);

Use chokidar to watch for file changes:

chokidar
  .watch('path/to/your/app/files')
  .on('change', path => {
    restart();
  });

In order to restart() a Node.js server, you must first shut it down by (1) closing all sockets and (2) by closing the server itself.

server.close(() => {
  start();
})

Lastly, you need to clear the cache of the require function by deleting the keys corresponding to changed files.

delete require.cache[filePath];