This section describes a trick for running a snippet of JavaScript code with Node.js while working on it.
As an example, let’s assume we want to experiment with the standard Node.js function util.format()
. We create the file mysnippet.mjs
, with the following content:
import * as util from 'node:util';
console.log(util.format('Hello %s!', 'world'));
How can we run mysnippet.mjs
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.mjs
:
nodemon mysnippet.mjs
Whenever we save mysnippet.mjs
, 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.
You can even try out nodemon without installing it, via the Node.js tool npx:
npx nodemon mysnippet.mjs
See §7.11.4 “Use case for URLs: detecting if the current module is “main” (the app entry point)”.
See §7.11.3 “Use case for URLs: accessing files relative to the current module”.