hot reload node js code example

Example 1: nodejs express hot reload

$ npm install nodemon -g
$ nodemon app.js

Example 2: js implement hot reload

const fs = require('fs')
const child = require('child_process')

// watch the target file
const watcher = fs.watch('app.js')
// create a child process for the target application
let currentChild = child.fork('app.js')

watcher.on('change', () => {
  // we assure we have only one child process at time
  if (currentChild) {
    currentChild.kill()
  }
  // reset the child process
  currentChild = child.fork('app.js')
})