Modules and ES / CommonJS Module Systems#
To build real applications, you’ll organize code across files using modules.
Node.js originally used CommonJS modules:
// util.js
function greet(name) {
return `Hello, ${name}!`;
}
module.exports = { greet };
// index.js
const { greet } = require('./util');
console.log(greet('Alice'));
With newer versions, Node also supports ES modules (via .mjs files or "type": "module" in package.json):
// util.mjs
export function greet(name) {
return `Hello, ${name}!`;
}
// index.mjs
import { greet } from './util.mjs';
console.log(greet('Bob'));
Understanding module resolution helps you avoid relative path errors and circular dependencies.
Also, Node’s module caching ensures that require or import calls are fast and idempotent, improving runtime efficiency.
How to build a basic Node.js server#
Let’s learn how to get started with Node.js by creating a simple Node.js file. In this example, we will be setting up our computer to work as a server!
Step 1: Install Node.js and NPM#
First, you need to go to the site Node.js site and download the files.
Follow the installation prompts and restart your machine for best results.
Another way you can install Node.js is to use a package manager.
Then, test that it’s working by printing the version using the following command:
> node -v
You should also test npm by printing the version using the following command:
> npm -v
Step 2: Create a file#
Once you have installed Node.js properly, create a Node.js file. In this example, we have named it first.js. We then add the following code and save the file on your computer.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
This code is essentially telling the computer to print “Hello World!” when accessed on port 8080.
Step 3: Run your Node.js program#
This file needs to then be run by Node.js. Do this by starting your command line interface, writing node first.js, and clicking enter:
node first.js
Awesome! Now your computer is set up as a server, so when you accesses the computer on port 8080, the “Hello World!” message will print.
To see this in real time, open your browser, and type: http://localhost:8080.
HTTP Server, Routing, and Middleware Basics#
You can use Node.js’s built-in http module to create a basic web server and handle routing.
Here’s a quick example:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/hello') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello from Node.js');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
}
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
For slightly more structure, you can implement a simple middleware pattern:
const middlewares = [];
function use(fn) {
middlewares.push(fn);
}
function handle(req, res) {
let idx = 0;
function next() {
const middleware = middlewares[idx++];
if (middleware) middleware(req, res, next);
}
next();
}
// usage
use((req, res, next) => {
console.log(`Request: ${req.method} ${req.url}`);
next();
});
use((req, res) => {
res.writeHead(200);
res.end('Hi!');
});
This pattern foreshadows frameworks like Express.
A strong “What is Node.js” guide should include this to show how HTTP handling flows in raw Node.js before abstraction layers are introduced.