What is the require() function in Node.js?

Why Interviewers Ask This

This is a classic screening question for Node.js roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.

Answer

require() is Node.js's built-in function for loading modules in the CommonJS module system. It takes a module identifier and returns the exported value. Module identifiers can be: (1) Built-in modules: require("fs"), require("http") — no path needed; (2) npm packages: require("express") — Node.js looks in node_modules/; (3) Local files: require("./utils") — relative path with or without .js extension. require() is synchronous — it loads the module, executes it, and returns module.exports before continuing. Node.js caches modules after the first load — subsequent require() calls for the same module return the cached export without re-executing the module file. This makes circular dependencies possible (though tricky) and module-level state work as singletons.

Pro Tip

This topic has Node.js-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.