How Node really works · Chapter 5 of 34

Modules and packages

By the end of this chapter you can mix CommonJS and ES modules, say how Node loads a file and which file a package hands out, and read the scripts and version ranges in a package.json. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: How Node runs
  • 6 tasks
  • Node.js
  • In the all labs plan

The first 2 chapters of How Node really works are free. This one comes with the all labs plan.

Why you need this

Tapri's first backend was written in CommonJS, and old code still loads the price list, prices.cjs, with require. New code is ES modules. Kabir wants both to work side by side while you migrate, and tools for the package.json files that decide how everything loads.

Without them you get "works on my machine" bugs: a require in a .js file stops with a ReferenceError, an edited config never reaches a running server, a deep import fails with ERR_PACKAGE_PATH_NOT_EXPORTED, and a caret range lets in a breaking release.

What you build: 6 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    prices.cjs: export the price list the CommonJS way

    In prices.cjs, finish priceOf(item): it returns the price of one item on MENU (priceOf('masala chai') is 40), and throws an Error whose message names the item when it is not on the menu, for example Not on the menu: cold coffee.

    Hand out MENU, unchanged, and priceOf the CommonJS way, so require of prices.cjs gets both. Inherited keys are not on the menu: priceOf('toString') must throw too.

  2. Task 2

    moduleKind: how will Node load this file?

    Write moduleKind(filename, packageType). It returns 'esm' or 'commonjs', how Node loads that file. packageType is the type field of the nearest package.json: 'module', 'commonjs', or undefined when there is none or it is left out.

    A .mjs file is always 'esm' and a .cjs file always 'commonjs', whatever the type. A .js file is 'esm' only when the type is 'module'; with 'commonjs' or no type at all it is 'commonjs'.

  3. Task 3

    freshRequire: reload a CommonJS module past the require cache

    Write freshRequire(path), where path is the absolute path of a CommonJS file. It loads the file again from disk even if it is already in the require cache, and returns its new module.exports, a different object from the cached one.

    The fresh copy takes the old one's place in the cache, so every later plain require of that path returns the same fresh object.

  4. Task 4

    resolveExport: which file a package hands out

    Write resolveExport(pkg, subpath, condition). pkg is a parsed package.json, subpath is '.' or './something', and condition is 'import' or 'require'. It returns the file, as a string such as './dist/index.js'.

    With no exports field, '.' gives pkg.main, or './index.js' when there is no main, and any other subpath is returned as it is. A string exports is that file, for '.' only. An exports object whose keys start with '.' maps subpaths to targets; any other exports object (keys such as import, require, default) is the target for '.'. A target is a file string, or an object of conditions where the key equal to condition wins and 'default' is the fallback; other conditions, such as node, are ignored here (real Node would also accept node).

    A subpath that is not exported, or a target with neither the condition nor default, throws an Error whose code property is 'ERR_PACKAGE_PATH_NOT_EXPORTED'.

  5. Task 5

    scriptPlan: what npm run will actually run

    Write scriptPlan(pkg, name). It returns the commands npm run <name> executes, as an array in this order: the pre<name> script if pkg has one, the script itself, then post<name> if pkg has one, whatever order the keys are written in.

    When pkg has no script called name, including when it has no scripts field at all, it throws an Error with the message Missing script: "<name>" (with the double quotes), for example Missing script: "deploy".

  6. Task 6 · interview question

    Interview: satisfies, does a version fit a caret, tilde or exact range?

    Write satisfies(version, range), returning true or false. version is MAJOR.MINOR.PATCH, like '1.4.2'. range is an exact version ('1.2.3', only that version), a tilde range ('~1.2.3', at least 1.2.3 with the same major and minor) or a caret range ('^1.2.3', at least 1.2.3 with the same major).

    Before 1.0 the caret is stricter: the leftmost non-zero part of the range may not change, so a caret on 0.MINOR.PATCH keeps the minor, and a caret on 0.0.PATCH allows only that version. Compare the parts as numbers, so 1.10.0 is newer than 1.9.0 and 10.0.0 is a different major from 9.0.0.

What you will learn

  • CommonJS and ES modules: module.exports and require beside export and import, and how Node picks a file's format.
  • The require cache: why a module runs only once.
  • package.json: exports, main and scripts.
  • Semver ranges: what ^, ~ and an exact version let in.

More in How Node runs

Build "Modules and packages" yourself

Tapri’s order server must never stall at the 4 pm rush. You learn why it would. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of How Node really works are free. This one comes with the all labs plan.