TechLearn Hub

Learn Technology in Simple English

What Is Node.js? A Beginner's Guide

Node.js is an important technology for developers who want to build web servers, APIs, backend services and other applications using JavaScript. This guide explains the main concepts, provides practical examples and suggests projects for beginners.

You do not need to understand every advanced concept immediately. Start with the fundamentals, practise the examples in a suitable development environment and gradually build more complex projects.

What you will learn: Node.js fundamentals, npm, modules, asynchronous programming, HTTP servers, Express.js, APIs, databases, security and a beginner-friendly learning path.

What Is Node.js?

Node.js is a JavaScript runtime environment that allows developers to run JavaScript outside a web browser.

JavaScript is commonly associated with websites and web browsers. Node.js makes it possible to use JavaScript for backend applications, servers, APIs, command-line tools and many other types of software.

Simple explanation: JavaScript is the language. Node.js provides an environment for running that language outside the browser.

Why Is Node.js Important?

Node.js became popular partly because developers can use JavaScript for both the frontend and backend of an application.

For example, a developer can use JavaScript in a browser to create the user interface and Node.js on a server to process requests and communicate with databases.

  • It uses JavaScript.
  • It is widely used for web applications.
  • It can be used to create APIs.
  • It can communicate with databases.
  • It supports a large ecosystem of packages.
  • It is useful for many input/output-heavy applications.
  • It can support real-time applications when combined with suitable tools.

Is Node.js a Programming Language?

No. Node.js itself is not a programming language. JavaScript is the programming language, while Node.js is the runtime environment that lets JavaScript execute outside a browser.

Node.js and JavaScript

JavaScript Node.js
A programming language A runtime environment for JavaScript
Often runs in web browsers Runs JavaScript outside the browser
Can control website interactions Can power servers, scripts and backend services
Browser code can use browser APIs Node.js code can use Node.js APIs and operating-system capabilities

How Node.js Works

Node.js uses the V8 JavaScript engine, which is also used by the Chrome browser. Node.js adds APIs that let JavaScript programs work with files, networks, servers and other system resources.

Node.js uses an event loop and asynchronous input/output operations to handle many connections efficiently. This does not mean every operation is automatically fast: CPU-intensive work can still block the event loop if it is not designed appropriately.

Installing Node.js

To use Node.js on a compatible computer, visit the official Node.js website and follow the installation instructions for your operating system. Choose a supported release appropriate for your project.

Official website: Node.js

After installation, open a terminal or command prompt and check the installed version:

node --version

You can also check the npm version:

npm --version
Important: These commands are intended for a terminal in an environment where Node.js is installed. A normal mobile browser cannot run them directly. If you are using a phone, you may need a compatible coding environment or a remote development workspace.

Your First Node.js Program

Create a file named app.js in your project folder.

Add this code:

console.log("Hello from Node.js!");

Run it from your terminal:

node app.js

The output should be:

Hello from Node.js!

Node.js Variables

Because Node.js runs JavaScript, you can use JavaScript variables and other language features.

const name = "TechLearn Hub";
let visitors = 100;

console.log(name);
console.log(visitors);

Use const when a variable will not be reassigned and let when reassignment is needed.

Functions in Node.js

Functions allow you to organise reusable code.

function greet(name) {
  return "Hello " + name;
}

console.log(greet("Student"));

Asynchronous Programming

Some operations take time, such as reading a file, accessing a database or communicating with another server. Asynchronous programming helps an application manage such work without unnecessarily blocking other tasks.

Modern JavaScript commonly uses promises and async / await to work with asynchronous operations.

async function getData() {
  const result = await someOperation();
  console.log(result);
}
Note: someOperation() is a placeholder, not a built-in Node.js function. Replace it with a real asynchronous operation that returns a promise. Production code should also handle errors.

A more complete pattern is:

async function main() {
  try {
    const result = await Promise.resolve("Data loaded");
    console.log(result);
  } catch (error) {
    console.error("Could not load data:", error);
  }
}

main();

What Is npm?

npm is the standard package manager commonly used with Node.js. It helps developers install and manage packages and run project scripts.

For example, to install Express in a project:

npm install express

Run this command from the project directory. npm will normally record the dependency in the project's package.json file.

Creating a Node.js Project

A Node.js project commonly has a configuration file named package.json.

Create one interactively with:

npm init

For a quick setup using default answers, use:

npm init -y

Understanding package.json

The package.json file can contain important project information, including:

  • Project name and version
  • Description
  • Scripts for common tasks
  • Dependencies
  • Development dependencies
  • Other package configuration

The package-lock.json file, when created, records specific dependency versions to help keep installations consistent.

Node.js Modules

Modules help developers organise code into separate files and components. Node.js includes built-in modules that can be used without installing additional packages.

Examples include:

  • fs — file-system operations
  • http — HTTP servers and clients
  • path — working with file paths
  • os — operating-system information
  • url — URL utilities
  • events — event handling

Node.js projects can use CommonJS syntax such as require(), or ECMAScript module syntax such as import. Which syntax works depends on the project configuration and file type.

The fs Module

The fs module provides ways to work with files. This example uses CommonJS syntax to create or replace a text file.

const fs = require("node:fs");

fs.writeFileSync(
  "example.txt",
  "Hello from Node.js",
  "utf8"
);

The file is written relative to the process's current working directory. Synchronous file operations are useful in simple examples, but asynchronous operations are often preferable for server workloads.

Reading Files

const fs = require("node:fs");

const data = fs.readFileSync(
  "example.txt",
  "utf8"
);

console.log(data);

The file must exist before this example runs. Otherwise, Node.js will throw an error.

Creating an HTTP Server

Node.js includes an HTTP module that can be used to create a basic web server without installing a separate web framework.

const http = require("node:http");

const server = http.createServer((req, res) => {
  res.writeHead(200, {
    "Content-Type": "text/plain; charset=utf-8"
  });

  res.end("Hello from my Node.js server!");
});

server.listen(3000, () => {
  console.log("Server running on port 3000");
});

Save the example as server.js and run it:

node server.js

If the server is running on your own computer, open this address in a browser on that computer:

http://localhost:3000
Remember: localhost refers to the device or environment making the request. A server running on your computer is not automatically accessible to everyone on the Internet. Public deployment requires appropriate hosting and security configuration.

What Is Express.js?

Express.js is a widely used web framework for Node.js. It provides a convenient way to define routes, handle HTTP requests and build APIs.

Inside an initialised Node.js project, install Express with:

npm install express

Creating a Simple Express Server

const express = require("express");

const app = express();

app.get("/", (req, res) => {
  res.send("Welcome to TechLearn Hub");
});

app.listen(3000, () => {
  console.log("Server running on port 3000");
});

Save this as server.js in a project where Express is installed, then run node server.js. Visit http://localhost:3000 to test it locally.

Node.js APIs

Node.js is widely used to create APIs. An API allows different software applications to communicate with each other through defined rules and interfaces.

For example, an Android application can send a request to a Node.js API. The server can validate the request, communicate with a database and return a response to the application.

HTTP Methods

APIs commonly use HTTP methods such as:

  • GET — retrieve a resource
  • POST — submit data or create a resource
  • PUT — replace a resource or update it according to the API design
  • PATCH — partially update a resource
  • DELETE — request removal of a resource

JSON in Node.js

JSON is a common data format used to exchange information between applications and APIs.

{
  "name": "John",
  "age": 25,
  "country": "Nigeria"
}

In JavaScript, JSON.parse() converts JSON text into a JavaScript value, while JSON.stringify() converts a supported JavaScript value into JSON text.

const user = {
  name: "John",
  country: "Nigeria"
};

const jsonText = JSON.stringify(user);
console.log(jsonText);

const parsedUser = JSON.parse(jsonText);
console.log(parsedUser.name);

REST APIs

REST is a style of designing networked APIs. A typical API might provide routes such as the following:

GET     /users
GET     /users/1
POST    /users
PUT     /users/1
PATCH   /users/1
DELETE  /users/1

These are illustrative routes, not endpoints that exist automatically. A developer must implement the routes and decide how data, permissions, validation and errors will be handled.

Node.js Middleware

Middleware is code that runs during the processing of a request. In Express, middleware can inspect requests, change request or response objects, end a response or pass control to the next middleware function.

Common uses include:

  • Authentication and authorisation
  • Logging
  • Input validation
  • Error handling
  • Security checks
  • Parsing request bodies

Node.js Error Handling

Applications should handle expected errors carefully and avoid exposing sensitive internal details to users.

try {
  const result = JSON.parse('{"status":"ok"}');
  console.log(result);
} catch (error) {
  console.error("Could not process the data.");
}

For asynchronous code, use suitable error handling for promises and async/await. Web servers should also provide appropriate error responses to clients.

Node.js and Databases

Node.js applications can communicate with many kinds of databases. The choice depends on the application's data model, performance needs, hosting environment and development requirements.

  • MySQL
  • PostgreSQL
  • MongoDB
  • SQLite
  • Microsoft SQL Server

A typical application may receive a request, validate the information, perform a database operation and return a response. Database access should be designed with permissions, error handling and secure configuration.

Node.js and MongoDB

MongoDB is a NoSQL database often used with Node.js applications. It stores data in document-oriented records.

A common technology combination is:

Node.js
   +
Express.js
   +
MongoDB

This combination can be used to build APIs and web applications. It is only one option; other databases and frameworks may be better for different projects.

Node.js and MySQL

Node.js can also communicate with relational databases such as MySQL. Depending on the chosen library, a developer can use Node.js to:

  • Create database connections or connection pools
  • Run SQL queries
  • Insert records
  • Update records
  • Delete records
  • Retrieve information

Use parameterised queries or prepared statements where supported instead of building SQL commands by joining untrusted user input.

Environment Variables

Applications often need configuration values such as database credentials, API keys and service URLs. Environment variables allow configuration to be provided separately from application source code.

For example, a Node.js application can read a value from the environment:

const port = process.env.PORT || 3000;

console.log("Configured port:", port);

The operating environment or deployment platform can supply the PORT value. Other variables can be used for database configuration and external services.

Security tip: Never publish private API keys, passwords or database credentials in a public repository. Do not send secret values to the browser. In frontend frameworks, variables with a public prefix such as NEXT_PUBLIC_ in Next.js are intended to be exposed to client-side code, so they must not contain secrets.

If you use a local environment file, keep it out of public repositories and configure your hosting provider's secret-management settings properly.

Node.js Security

Security is important when building Node.js applications, especially when they accept requests from the public Internet or handle personal information.

  • Validate and appropriately sanitise user input.
  • Protect authentication credentials.
  • Use HTTPS for production traffic.
  • Keep Node.js and dependencies supported and updated.
  • Avoid exposing stack traces and sensitive information to users.
  • Use secure authentication and authorisation methods.
  • Apply database permissions based on least privilege.
  • Protect API keys and database credentials.
  • Use rate limits where appropriate to reduce abuse.
  • Review dependencies and their security advisories.

Node.js Authentication

Authentication helps an application verify who a user is. Authorisation determines what that authenticated user is allowed to do.

Common authentication concepts include:

  • User registration and login
  • Password hashing
  • Sessions and cookies
  • Access tokens
  • Multi-factor authentication
  • Authorisation and access control

Passwords should be stored using an appropriate password-hashing algorithm, not as plain text. Applications should follow current security guidance when handling sessions, cookies and tokens.

Node.js Debugging

Debugging means finding and fixing problems in software. Developers can use tools and techniques such as:

  • Console logging
  • Node.js debugging tools
  • Code-editor debuggers
  • Automated tests
  • Logs and error reports

Node.js Testing

Testing helps developers check whether their applications behave as expected. Different projects may use different testing tools and frameworks.

Common testing types include:

  • Unit tests: check small functions or components.
  • Integration tests: check whether parts work together.
  • API tests: check server endpoints and responses.
  • End-to-end tests: check complete user workflows.

Node.js Command-Line Applications

Node.js is not limited to web servers. It can also create command-line applications and automation scripts.

Examples include:

  • File-management tools
  • Automation scripts
  • Development tools
  • Project generators
  • Data-processing utilities

Node.js Real-Time Applications

Node.js can be used for applications that need real-time communication, often with an additional library or protocol.

Examples include:

  • Chat applications
  • Live notifications
  • Online games
  • Real-time dashboards
  • Collaborative applications

Node.js and WebSockets

WebSockets allow a client and server to maintain a connection for two-way communication. They are useful when an application needs frequent updates without repeatedly refreshing a webpage.

Node.js applications can use WebSocket libraries or frameworks such as Socket.IO, depending on the project's requirements. Socket.IO and the native WebSocket protocol are related but are not identical.

Node.js and Frontend Frameworks

Node.js is often used alongside frontend technologies and frameworks. Examples include:

  • React
  • Angular
  • Vue
  • Svelte

A frontend framework or library usually helps create the user interface, while a Node.js backend can provide APIs and server-side services. Some frameworks also use Node.js during development or server rendering.

Node.js and React

React is a JavaScript library for building user interfaces. Node.js can power backend services and APIs and can also run tools used to develop React applications.

Together, they can form part of a full-stack application, although React does not require a Node.js backend in every project.

Node.js Package Ecosystem

One of Node.js's strengths is its large package ecosystem. Developers can install packages for many tasks instead of building every feature from scratch.

Packages are available for:

  • Authentication
  • Database access
  • Web servers
  • File processing
  • Data validation
  • Testing
  • Security
  • API development

Popular Node.js Tools

  • npm: package management
  • Express: web framework
  • Socket.IO: real-time communication library
  • PM2: process management tool
  • Jest: JavaScript testing framework

Node.js Project Structure

A simple Node.js backend project might be organised like this:

my-project/
|
|-- node_modules/
|-- package.json
|-- package-lock.json
|-- server.js
|-- routes/
|-- controllers/
|-- models/
|-- middleware/
|-- tests/
└-- public/

The exact structure varies. Small projects may use only a few files, while larger applications often separate routing, business logic, data access, configuration and tests.

What Can You Build With Node.js?

  • Web servers
  • REST APIs
  • Mobile-app backends
  • Chat applications
  • Real-time applications
  • Authentication systems
  • Dashboards
  • Command-line tools
  • Automation tools
  • Online services

Node.js for Mobile Applications

Node.js can act as the backend of a mobile application. An Android application can communicate with a deployed Node.js API over the Internet.

The backend can handle tasks such as:

  • User accounts and authentication
  • Database operations
  • Application data
  • Notifications through suitable services
  • Payment-provider integrations
  • Server-side business rules

Node.js does not automatically create a complete Android app. The mobile interface must be built separately, and the backend needs to be hosted somewhere that the application can securely reach.

Node.js vs PHP

Node.js PHP
Runs JavaScript outside the browser Uses the PHP programming language
Often used for APIs, services and web backends Widely used for server-side websites and web applications
Commonly uses npm for package management Commonly uses Composer for package management
Can support asynchronous input/output patterns Capabilities depend on the PHP runtime and application architecture

Node.js vs Python

Node.js Python
JavaScript runtime environment Programming language with its own runtime
Often used for APIs and network services Often used for web development, automation, data science and AI
Commonly uses npm Commonly uses pip and other Python package tools
Uses JavaScript syntax and ecosystem Uses Python syntax and ecosystem

Advantages of Node.js

  • Allows JavaScript to be used outside the browser.
  • Has a large package ecosystem.
  • Is useful for building APIs and web services.
  • Can support real-time applications.
  • Has a large developer community.
  • Works across supported operating systems.
  • Can be used in both frontend development workflows and backend projects.

Challenges of Node.js

  • Asynchronous programming can be challenging for beginners.
  • Dependencies need to be maintained carefully.
  • CPU-intensive tasks may need workers or a different architecture.
  • Developers need to understand JavaScript as well as Node.js concepts.
  • Production services require attention to security, monitoring and deployment.

Who Should Learn Node.js?

Node.js may be useful for:

  • JavaScript developers
  • Web developers
  • Backend developers
  • Full-stack developers
  • API developers
  • Mobile-app developers
  • Students learning server-side programming

Node.js Learning Path

If you are a beginner, study these topics in order. Move to the next stage when you can explain and practise the previous one.

  1. Learn JavaScript variables, functions, arrays and objects.
  2. Learn Node.js fundamentals.
  3. Learn npm and package management.
  4. Understand modules and imports.
  5. Practise promises and asynchronous programming.
  6. Create a basic HTTP server.
  7. Learn Express.js and routing.
  8. Build and test REST APIs.
  9. Connect an application to a database.
  10. Learn authentication and authorisation.
  11. Study security and error handling.
  12. Build projects and learn how to deploy them.

Beginner Node.js Projects

Projects help you apply what you have learned. Start with something small, then add features as your skills improve.

  • Simple HTTP server: return a message from a server.
  • To-do API: create, read, update and delete tasks.
  • Notes API: store and retrieve notes.
  • Weather API client: request data from a weather service.
  • Blog backend: manage articles and categories.
  • Authentication demo: practise secure login patterns.
  • URL shortener: map short codes to longer URLs.
  • Simple chat application: explore real-time communication.

Common Node.js Mistakes

  • Putting passwords directly in source code.
  • Ignoring errors and rejected promises.
  • Failing to validate user input.
  • Installing unnecessary or untrusted packages.
  • Publishing private credentials.
  • Not understanding asynchronous code.
  • Using outdated dependencies without reviewing their status.
  • Assuming a local server is automatically available on the Internet.

Simple Node.js Cheat Sheet

Command Purpose
node --version Check the Node.js version
npm --version Check the npm version
npm init -y Create a basic package.json file
npm install express Install Express in the current project
npm uninstall express Remove Express from the project
node app.js Run the app.js file

Official Node.js Learning Resources

Use official documentation to confirm details, learn more advanced features and check current recommendations.

Frequently Asked Questions

Is Node.js a programming language?

No. Node.js is a runtime environment for executing JavaScript outside a web browser.

Can Node.js build websites?

Yes. Node.js can power web servers and backend systems used by websites. Additional tools may be used to generate pages and build user interfaces.

Can Node.js create APIs?

Yes. Developers commonly use Node.js, often with a framework such as Express, to create APIs.

Can Node.js work with databases?

Yes. Node.js can communicate with databases using appropriate drivers, libraries or other services.

Is Node.js only for backend development?

No. It can also run command-line tools, automation scripts and development tools. It is also used in workflows for building frontend applications.

Do I need JavaScript before learning Node.js?

Learning JavaScript first is strongly recommended because Node.js runs JavaScript. Understanding variables, functions, objects, modules and promises will make learning Node.js easier.

Is Node.js free?

Node.js is open-source software. However, hosting, databases and other services used by an application may have their own costs or usage limits.

Can I learn Node.js using a phone?

You can read documentation and study code on a phone. To execute Node.js programs, you will need a compatible environment, such as a supported mobile coding environment or a remote development workspace.

Can Node.js power an Android application?

Yes. Node.js can run the backend API that an Android app communicates with. The Android interface and the backend are separate parts of the system.

Conclusion

Node.js is a JavaScript runtime environment that allows developers to build server-side applications and many other types of software using JavaScript.

It is useful for web servers, APIs, real-time services, backend systems, command-line tools and mobile application backends.

For beginners, a practical learning path is to start with JavaScript, continue with Node.js fundamentals and npm, and then practise modules, asynchronous programming, HTTP, Express.js, APIs, databases and security.

Next step: Build a small Node.js project, test it carefully and gradually add new features. Practising with real examples is an effective way to develop your programming skills.

Back to top ↑