NodeJS Watch and Serve

Perry Mitchell / 2016-06-04 17:32:18
NodeJS Watch and Serve

It’s no se­cret that de­vel­op­ing with NodeJS is both sim­ple and highly pro­duc­tive. It’s ter­ri­bly easy to get started and there’s very lit­tle to do to be able to de­velop pow­er­ful com­mand line ap­pli­ca­tions. A com­mon ap­proach to rapidly de­vel­op­ing these ap­pli­ca­tions is watch­ing and re­load­ing when changes are made to the source code.

This is­n’t new, but thanks to the vi­brant ecosys­tem that is npm, there’s a cou­ple of pack­ages that make re­load­ing as you save a cinch.

The first tool I’d rec­om­mend is node­mon, which is a very easy-to-use watch­ing ap­pli­ca­tion. Nodemon watches for source changes in spec­i­fied lo­ca­tions and re­loads a spec­i­fied JavaScript en­try point. After in­stalling node­mon by run­ning npm install nodemon --save-dev, add an npm script called watch with a com­mand like nodemon --watch source/**/*.js source/index.js. Running npm run watch at this stage will ex­e­cute node­mon to watch all .js files in the source di­rec­tory, and when any are changed, source/index.js will be ter­mi­nated and restarted.

nodemon watch

If you’re build­ing a client li­brary or other types of as­sets for the web, an easy way to test these lo­cally is by serv­ing them dur­ing de­vel­op­ment. serve is a great tool to very quickly serve all con­tent within a di­rec­tory on a spe­cific port. I’d rec­om­mend in­stalling serve glob­ally with sudo npm install serve -g, as it’s great all-round tool, but it can easy ac­com­pany any li­brary as an npm script. Creating a script called serve with a com­mand such as serve -p 8080 build/ will serve your built as­sets on port 8080.

Together, node­mon and serve can as­sist you to quickly get into con­tin­u­ous de­vel­op­ment mode where your changes are served im­me­di­ately to the browser.

{
  "name": "myapp",
  "version": "0.1.0",
  "description": "My library",
  "main": "source/index.js",
  "scripts": {
    "build": "node source/index.js",
    "server": "serve -p 8080 ./build",
    "watch": "nodemon --watch source source/index.js"
  },
  "devDependencies": {
    "nodemon": "^1.9.2",
    "serve": "^1.4.0"
  }
}

Of course, these tools only scrape the sur­face when it comes to de­vel­op­ment se­tups. If you’re build­ing a more in­volved li­brary, larger work­flow tools like web­pack and web­pack dev server are def­i­nitely more suit­able.