Introduction to Back-end Development with Node.js

What is Back-end Development?

Every website can be split into two: the front-end and the back-end. The front-end is everything you see and interact with when you visit a website. While the back-end is what you don't see, the back-end saves and manages your data behind the scenes. Things like your profile, user data are all managed by the back-end.

Here's a real-life example: when you visit a website and want to create an account on the site, you're usually asked to fill in your name, username, email address, etc. After you provide all this information, you submit the form for your account to be created. What happens when you submit the form is that your browser sends all the information you provide to the back-end so that your information will be stored, and a profile or account will be created for you.

Once your profile is created, the back-end sends a response to the browser to redirect you to the login page so that you can access your newly created account.

Introduction to Node.js

Several programming languages can be used to write the back-end code of a website. Below is a list of the most popular ones,

  1. php

  2. JavaScript

  3. Python

  4. Go

In this guide, we will focus on JavaScript. However, it's important to note that JavaScript wasn't designed to write back-end code; it's meant for front-end alone. Its use in the back-end was made possible by Ryan Dahl in 2009 when he developed a runtime called Node.js

What is Node.js

Node.js is a JavaScript runtime (a program / an environment that lets you run another program) developed in 2009 to allow web developers to use JavaScript in the back-end.

How to Download and Install Node.js

You can download Node.js by visiting the official website at nodejs.org. Once you're on the site, click the Download Node.js (LTS) button.

nodejs.org homepage

Once the download is complete, open the file and follow the prompts to install it. Once successfully installed, open your terminal and run the command node -v. If you see a version, it means Node.js has been successfully installed. You can also run npm -v to see the version of npm (Node Package Manager, more on this later) installed.

Note: npm comes with Node.js, so you don't have to download/install it separately.

Hello World in Node.js

Now that you have installed Node.js, let's create your first program. To do this, open any text editor of your choice (VS Code is my favourite) and create a file named index.js. Inside the file, type console.log(“Hello World”). Afterwards, open up your terminal and go to the directory where your index.js file is saved and run the command, node index.js (You can also run node index, that is without the extension).

If there's no problem, you should see the output, Hello World in your console.

console.log("Hello World") in VS Code

Node.js Fundamentals

Node.js Modules

A module is a file that can be exposed/exported to other files and imported into other files. Node.js uses the module system to allow code reusability and maintenance.

There are 3 types of modules in Node.js

  1. Core/Built-in Modules

  2. Local Modules

  3. Third-party Modules

Also, there are 2 styles in Node.js for importing and exporting modules, namely CommonJS and EcmaScript Module (ESM)

CommonJS uses the method require for importing modules and module.exports to export modules, while ESM uses import to import modules and export to export and expose modules.

Core/Built-in Modules

Core or built-in modules are modules provided by the Node.js platform once installed. Here are three of the popular built-in modules in Node.js

  1. Path

The path module provides methods for working with file and directory paths.

Here’s a simple code snippet to demonstrate some of the methods provided by the path module:

const path = require("path");

// Example relative file path
const relativePath = "./files/report.txt";

// Get absolute path
const absolutePath = path.resolve(relativePath);
console.log("Absolute Path:", absolutePath);

// Get the file name
const fileName = path.basename(absolutePath);
console.log("File Name:", fileName);

// Get the directory name
const dirName = path.dirname(absolutePath);
console.log("Directory Name:", dirName);
  1. File System (fs)

The fs module allows you to interact with the file system on your machine. This module lets you read, write, delete, and manage files. The fs module supports both synchronous and asynchronous operations. Here’s a simple code snippet to read the content of example.txt in the current working directory.

const fs = require("fs");
const path = require("path");

// Path to the file (e.g., same folder as this script)
const filePath = path.join(__dirname, "example.txt");

// Read the file (async version)
fs.readFile(filePath, "utf8", (err, data) => {
  if (err) {
    console.error("Error reading file:", err.message);
    return;
  }

  console.log("File content:\n", data);
});
  1. HyperText Transfer Protocol (http)

The http module enables Node.js to create an HTTP server and handle requests and responses. We’ll look at how to create an HTTP server later. For now, let’s talk about npm.

Npm

npm is an acronym for Node Package Manager. It is a repertoire for third-party modules (also called packages). With npm, you can find any package that does anything. You don't have to uninstall npm separately, as it comes with the Node.js installation. Unlike built-in modules, you have to download a package from npm to use it in your project. Here's a simple example of how to download and use a package from npm.

Suppose in your project, you need to convert texts to a URL-friendly slug. Instead of creating your custom text-to-slug converter, you can download an npm package known as slugify and use it in your project. To download a package from npm, you have to run the command npm install <package name> , e.g. npm install slugify. Once installed, the package name and version are added to a package.json file in your current working directory. Then you can use the package as follows:

const slugify = require("slugify");

const title = "Hello World! This is an NPM demo.";

const slug = slugify(title);

console.log(slug);

Creating a web server with Node.js

A web server listens for a request (such as when you visit a website) and sends back a response (e.g. an HTML page).

To create a basic web server in Node.js, create a file index.js and add the code below.

const http = require("http");

// Create an HTTP server
const server = http.createServer((req, res) => {
  // Set the status code to 200 (OK) and the response header to plain text
  res.writeHead(200, { "Content-Type": "text/plain" }); // Send the response body and end the request

  res.end("Hello, this is my first Node.js web server!");
});

// Make the server listen on port 3000
server.listen(3000, () => {
  // Log a message when the server is up and running
  console.log("Server is running at http://localhost:3000");
});

To test it, run the file with node index.js and go to localhost:3000

Conclusion

This article provides a very basic introduction to back-end development using Node.js, but there's still more to back-end development and Node.js than what was covered here. To get a detailed roadmap on Node.js and back-end development in general, consider checking out this detailed roadmap by Kamran Ahmed on roadmap.sh

1
Subscribe to my newsletter

Read articles from Abdul-Hafiz Aderemi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Abdul-Hafiz Aderemi
Abdul-Hafiz Aderemi