tezvyn:

Resolving core vs relative module specifiers

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

knowledge of module resolution rules.

OUTLINE

'fs' is a built-in core module loaded by name with top priority; './my-file.js' is a relative path resolved from the current file.

WHAT THIS TESTS This verifies that you know how Node decides what a require string points to. The resolution algorithm has clear precedence rules, and confusing core modules with packages or relative files is a telling gap.

A GOOD ANSWER COVERS A specifier without a path prefix, like fs, is a bare specifier. Node checks its set of built-in core modules first; fs, path, http, and similar are compiled into the Node binary, so requiring them returns the built-in immediately with no filesystem access and the highest priority. A specifier starting with ./ or ../ is relative and is resolved against the directory of the file doing the requiring. Node tries the literal path, then appends extensions such as .js, .json, and .node, and if the target is a directory it looks for a main field or index file. A bare name that is not core triggers the node_modules lookup, walking up parent directories until the package is found.

COMMON WRONG ANSWERS Saying fs is installed in node_modules, that core modules can be shadowed by a same-named local package, or that relative and bare specifiers follow the same search path. Another error is forgetting the extension and index resolution steps for relative paths.

LIKELY FOLLOW-UPS The full node_modules walk, the node: prefix for core modules, how package.json exports maps change resolution, and how ES module resolution differs from CommonJS.

ONE CONCRETE EXAMPLE From a file at src/api/routes.js, require('fs') returns the built-in immediately, while require('./users.js') resolves to src/api/users.js. If you instead wrote require('users'), Node would ignore that local file and search src/api/node_modules, then src/node_modules, then node_modules, looking for an installed package named users.

Read the original → nodejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.