Module 1: Node Foundations
JavaScript on the Server
For many years JavaScript lived only inside web browsers. If you wanted to build the server side of a website, you learned a second language such as PHP, Java or Python. Node.js changed that. It lets you run JavaScript on a server, so one language can power the whole application, from the button a user clicks to the database query behind it. That is the foundation of everything in this course.
What Node.js actually is
Node.js is a runtime: a program that runs JavaScript outside the browser. It was first released in 2009 and is built on V8, the same JavaScript engine used in Google Chrome. Node adds the things a server needs that browsers do not provide, such as reading and writing files, opening network connections, and accessing environment variables. It also leaves out browser-only features: there is no document, no window and no web page to change.
| In the browser | In Node.js |
|---|---|
document, window, the DOM | Not available |
| Limited, sandboxed storage | Full file system access with fs |
| Runs code the user downloaded | Runs code you control on your server |
fetch, timers, console | Also available (fetch is built in on current versions) |
Page loads scripts with <script> | Files load each other with modules |
Why Node handles many users well
Most server work is waiting: waiting for the database, for a file, for another API such as a payment provider. Node uses a single main thread with an event loop and non-blocking input/output. When your code asks for something slow, Node starts the operation, moves on to other work, and comes back when the result is ready. One Node process can therefore serve many connections at once without creating a thread for each.
Think of a busy food kiosk in Nairobi's CBD with one very efficient cashier. The cashier takes your order, passes it to the kitchen and immediately serves the next customer instead of standing still while your chapati cooks. When the food is ready, you are called. Node's event loop is that cashier.
The flip side: if you give the cashier a long task they must do personally, such as counting a huge bag of coins, the whole queue stops. In Node, heavy calculations on the main thread, such as resizing large images or processing a giant file synchronously, block every other request. Node is excellent for APIs, real-time apps and services that coordinate other systems. For CPU-heavy work, you move it to worker threads, a background job queue or another service.
Installing Node and running your first script
Download Node.js from the official site, nodejs.org. Choose the LTS (Long Term Support) version, which is the stable choice for most projects. Check the installation in your terminal:
node --version
npm --version
Now create a file called hello.js:
const os = require('os');
const name = process.argv[2] || 'developer';
console.log(`Hello, ${name}!`);
console.log(`This computer has ${os.cpus().length} CPU cores.`);
console.log(`Node version: ${process.version}`);
Run it with node hello.js Wanjiru. You will see a greeting, the number of CPU cores and the Node version. Two things to notice: require('os') loads one of Node's built-in modules, and process is a global object that gives you information about the running program, including command-line arguments and environment variables.
Worked example: seeing non-blocking code
Create order.js and predict the output before you run it:
const fs = require('fs');
console.log('1. Start');
fs.readFile(__filename, 'utf8', (err, text) => {
if (err) return console.error(err);
console.log(`3. File has ${text.length} characters`);
});
setTimeout(() => console.log('4. Timer finished'), 100);
console.log('2. End of script');
The output appears in the order 1, 2, 3, 4. Node starts reading the file and setting the timer, finishes the rest of the script, and then runs the callbacks when their results are ready. This "start now, finish later" style is the single most important idea in Node, and you will see it in every lesson that follows.
Common mistakes to avoid
- Using browser objects on the server.
document.getElementByIdwill throw an error in Node. - Using synchronous functions in servers.
fs.readFileSyncis fine in a one-off script, but inside a request handler it blocks every other user. - Expecting code to run top to bottom. Callbacks and promises run later. Code that depends on a result must wait for it.
- Installing an odd version. Stick with an LTS release unless you have a specific reason not to.
Exercise
Install the current LTS version of Node.js and confirm it with node --version. Create hello.js from this lesson and run it with your own name. Then create order.js, write down the order you expect the four messages to appear in, run it and compare. Finally, change the timer to 0 milliseconds and see whether the order changes.
Key points
- Node.js runs JavaScript on the server using Chrome's V8 engine.
- Node has file, network and process features but no DOM or window.
- The event loop lets one process handle many connections by not waiting on slow I/O.
- Never block the main thread with long synchronous work inside a server.