Explain Codes LogoExplain Codes Logo

What is "require" in JavaScript and NodeJS?

javascript
module-system
require-function
nodejs
Anton ShumikhinbyAnton Shumikhin·Jan 21, 2025
TLDR

The require function in Node.js is a built-in function for module importation. It operates synchronously, loading the module's exports into your program and allowing you to use its methods and properties.

Consider this:

const http = require('http'); // Importing the "http" module const server = http.createServer((req, res) => { //Creating a server, it's easier than making pasta, literally! res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); // Classic Hello World, because why not! }); server.listen(3000); // The server is listening at port 3000, not it doesn't have ears, that's just a metaphor!

This simple example demonstrates how the http module is imported using require, and how a server can be created accordingly. Using require is a key practice for building modular and maintainable code in Node.js.

Grasping Node.js module system

Let's get our hand dirty with the meat and potatoes of Node.js - The Module system. To keep it simple, when a Node.js process boots up, it initializes a module cache. Any subsequent calls require fetch from here instead of the actual module, giving a jolt to the speed, similar to your favourite coffee on a Monday!

In the grand scheme of Node.js, require is the lifeblood of the CommonJS module system. It does away with <script> tags and propels a modular, scoped, and thread-safe workspace.

Scope in the wild

Each module is hand-wrapped, not with environmentally destructive plastic, but in a function scope. It locks all your variables and functions in a fortress, leaving them visible only if you decide to export them. This is requireing with principles!

Feast your eyes on this multi-module import:

const express = require('express'); // Not the Pony Express, this one only delivers your packages! const bodyParser = require('body-parser'); // It's a bodyguard... for your "body"! const app = express(); app.use(bodyParser.json()); // And voila, "body" is secured! // Start building the rest of your awesome app now!

One Package, One Home

In the world of Node.js, there's a private neighborhood called the node_modules where your packages chill out. npm install <package-name> hits the NPM registry like a local supermarket and drops the packages in here. This is also the snuggly little place require checks first when you ask for a module.

Meeting 'require' in real life

Ever heard of revealing module pattern? This Node.js trendsetter lets your module export an object littered with properties and functions. It's a subtle way to let everyone know what's up for grabs and what isn't.

Now, let's discuss about the modules. There are native modules (Like Austrians in Austria) such as fs and http that come bundled with Node.js. On the other hand, you have third-party modules (tourists!) like lodash or axios which are fetched from the NPM registry.

Smack in the middle of this sits require, a function that loads modules synchronously. That means, it's like a dog waiting for you at the door until you come home. It halts the code execution till the module is loaded. Though ideal during setup phase, it might drag the performance during runtime. For asynchronous loading, consider dynamic import() calls in lieu of require.

The Alternatives

Node.js swings the require bat, but in the browser's playground, things are a little different. In such batting cages, require is replaced by newer hotshots like RequireJS or ES6 modules (import/export).

To 'require' or not to 'require'

Browsers are like stubborn kids. They need <script> tags, ESM modules, or loaders like RequireJS or SystemJS to load JavaScript files. However, for server-side or bundling with webpack, Browserify etc., require is your best bet.

Meanwhile, JavaScript continues to evolve and Node.js has started to flirt with ES6 syntax, marking the dawn of a unified module system that works seamlessly on the server and in the browser.