Shell scripting with Node.js
You can buy the offline version of this book (HTML, PDF, EPUB, MOBI) and support the free online version.
(Ad, please don’t block.)

17 Shell scripting recipes

17.1 Interactively editing code snippets via nodemon

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

17.1.1 nodemon

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.

17.1.2 Trying out nodemon without installing it

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

npx nodemon mysnippet.mjs

17.2 Detecting if the current module is “main” (the app entry point)

See §7.11.4 “Use case for URLs: detecting if the current module is “main” (the app entry point)”.

17.3 Accessing files relative to the current module

See §7.11.3 “Use case for URLs: accessing files relative to the current module”.