Node.js CommonJS
CommonJS modules use require and module.exports. Existing Node projects may use that format even when new teaching examples prefer ESM.
How it works
The .cjs extension states the format explicitly. ESM and CommonJS differ in loading rules, available globals and interoperability details; renaming every require call is not a complete migration. This example loads a controlled CommonJS helper from an ESM entry point with createRequire. It keeps the exported object small and does not rely on heuristic named-export detection across the format boundary.
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 commonjs.mjs in a separate empty exercises folder and run node commonjs.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
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 { createRequire } from 'node:module';
try {
const file = join(folder, 'label.cjs');
await writeFile(file, "module.exports = {label:'field-kit desk'};\n", { flag: 'wx' });
const require = createRequire(import.meta.url);
console.log(require(file).label);
} finally {
await rm(folder, { recursive: true, force: true });
}
Expected result
field-kit desk
The imported object is the actual module.exports value. The script demonstrates one intentional interoperability boundary rather than claiming that every CommonJS dependency can be migrated with the same wrapper.
Use the Node.js API reference for the precise version contract.