bhylu.com

Advertisements

Node.js ES Modules

An ES module states what it imports and exports. The .mjs extension makes the module format explicit even without a surrounding package.json.

How it works

Use named exports when consumers should depend on a small public contract rather than the internal shape of a file. Imports use file URLs and explicit relative extensions in Node’s native ESM resolver. This complete example writes one owned helper into a fresh temporary directory, imports it, and cleans up only that directory. Real projects normally keep the helper as a normal source file instead of creating it dynamically.

Run the code

Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as esm.mjs in a separate empty exercises folder and run node esm.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs.

Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.

Example

esm.mjs

import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const folder = await mkdtemp(join(tmpdir(), 'bhylu-node-'));
import { writeFile } from 'node:fs/promises';
import { pathToFileURL } from 'node:url';
try {
  const file = join(folder, 'quantity.mjs');
  await writeFile(file, 'export const remaining = (stock, used) => stock - used;\n', {
    flag: 'wx',
  });
  const { remaining } = await import(pathToFileURL(file).href);
  console.log(remaining(5, 2));
} finally {
  await rm(folder, { recursive: true, force: true });
}

Expected result

3

The imported function has one clear responsibility. pathToFileURL handles platform path details instead of manually constructing a file URL. The temporary fixture is an execution test, not a recommendation to generate source from received input.

Use the Node.js API reference for the precise version contract.