Node.js Basics

Node.js is a JavaScript runtime built on Chrome's V8 engine that allows you to run JavaScript on the server side. It enables building scalable network applications with event-driven, non-blocking I/O models.

Illustration of Node.js Basics
Illustration of Node.js Basics

💡 What is Node.js?

Node.js lets you execute JavaScript outside the browser, making it possible to build backend services, command-line tools, and more using JavaScript.

Key Features of Node.js

  • Event-driven and Asynchronous: Handles many connections concurrently without blocking.
  • Single-threaded: Uses a single thread with event looping for handling requests efficiently.
  • Built-in Modules: Provides modules like fs for file system, http for server, and path for file paths.
  • NPM: Comes with Node Package Manager for managing third-party libraries.

Running JavaScript with Node.js

To run a JavaScript file using Node.js, use the terminal command:

📌 Deep Dive: Basic Execution

BASH
node filename.js

Example hello.js:

📌 Deep Dive: Simple Console Output

JAVASCRIPT
console.log('Hello from Node.js');
Output
Hello from Node.js

Commonly Used Built-in Modules

Node.js Core Modules Overview
ModulePurpose
fsFile system operations (reading/writing files)
httpCreating web servers and handling HTTP requests
pathWorking with file and directory paths
osOperating system-related utility methods
eventsEvent emitter for handling asynchronous events

Importing Modules

Use require() to include modules in Node.js:

📌 Deep Dive: Requiring Modules

JAVASCRIPT
const fs = require('fs');
const path = require('path');

💡 CommonJS Modules

Node.js uses the CommonJS module system by default, which relies on require and module.exports.

Creating a Simple HTTP Server

One of the first things to try in Node.js is creating a basic web server:

📌 Deep Dive: Minimal HTTP Server

JAVASCRIPT
const http = require('http');

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, Node.js Server!');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});
Output in Terminal
Server running at http://localhost:3000/

⚠️ Important

Node.js scripts run in a single thread. Use asynchronous APIs to avoid blocking the event loop and maintain performance.

Summary

  • Node.js allows running JavaScript outside the browser for backend development.
  • Use node filename.js to run scripts.
  • Core modules like fs and http provide essential functionality.
  • Modules are loaded using require().
  • Build servers easily with the http module.