Running code snippets via Node.js and nodemon

[2018-08-15] dev, javascript, nodejs, nodemon
(Ad, please don’t block)

This blog post describes a trick for running a snippet of JavaScript code with Node.js while working on it.

nodemon  

As an example, let’s assume we want to experiment with the standard Node.js function util.format(). We create the file mysnippet.js, with the following content:

const util = require('util');

console.log(util.format('Hello %s!', 'world'));

How can we run mysnippet.js while we are working on it?

We first install the npm package nodemon:

npm install -g nodemon

Then we can use it to continuously run mysnippet.js:

nodemon mysnippet.js

Whenever we save mysnippet.js, nodemon runs it again. That means that we can edit that file in an editor and see the results of our changes whenever we save it.

Trying out nodemon without installing it  

You can even try out nodemon without installing it, via the Node.js tool npx:

npx nodemon mysnippet.js