Node.js — Concept, Working, and Features
Node.js is a powerful platform used for building scalable network applications. It allows developers to use JavaScript to write server-side code, which was traditionally only used for client-side scripting in web browsers.
Concept of Node.js
Working of Node.js
Node.js operates differently than traditional web-serving techniques:
Key Features of Node.js
Components of Node.js
Node.js is composed of several key components that work together to provide a high-performance, asynchronous environment for executing JavaScript on the server side.
HTTP/HTTPS— For creating web servers and handling requests.FS (File System)— For reading, writing, and deleting files.Path— For handling and transforming file paths.URL— For parsing and resolving URL strings.
Required Modules — Creating a Server and Handling Request-Response
In Node.js, the http module is a core built-in module that allows Node.js to transfer data over the HTTP protocol. It is primarily used to create a web server that listens to server ports and gives a response back to the client.
Creating a Server — http.createServer()
The http.createServer() method is used to create an instance of an HTTP server.
var http = require('http');
http.createServer(function (req, res) {
// Logic goes here
}).listen(8080);
.listen() method specifies the port on which the server listens for incoming requests.
The Request Object (req)
The req (Request) argument represents the request from the client — an object containing information about the incoming data from the web browser.
- Purpose: Used to get information such as the URL, headers, and data sent by the client.
- Example:
req.urlholds the part of the URL after the domain. Visitinglocalhost:8080/summermakesreq.urlreturn/summer.
The Response Object (res)
The res (Response) argument represents the response the HTTP server sends back when it receives a request.
Summary Example
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'}); // Header
res.write('Hello World!'); // Body
res.end(); // Finalize
}).listen(8080);
"Hello World!" text sent back to the user's screen.
http module enables Node.js to act as a web server. createServer() handles incoming requests, while req and res objects manage request data and send responses back to the client.
require() Function and User-Defined Modules
The require() Function
In Node.js, the require() function is a built-in tool used to include (import) code from other files or modules into your current file. It reads a JavaScript file, executes it, and allows you to use its functions and variables — preventing you from writing all code in one single file.
var myModule = require('module_name_or_path');
Types of Modules it Can Load
require('http')require('express')User-Defined Modules
User-defined modules are custom JavaScript files created by the developer. They help keep the project organized, clean, and reusable. Creating and using a module involves two steps:
- Step 1 — Exporting: To make a function available to other files, publish it using the
module.exportskeyword. - Step 2 — Importing: To use that custom file, use
require()with the exact file path (using./for files in the same folder).
Example
// Create a simple addition function
var addNumbers = function(a, b) {
return a + b;
};
// Export it so other files can use it
module.exports = addNumbers;
// Require the local module
var mathModule = require('./math.js');
// Use the function
var result = mathModule(5, 10);
// Output: 15
console.log(result);
require() function imports code from core, third-party, or user-defined modules. User-defined modules use module.exports to share functions and require('./path') to import them, keeping code clean and reusable.
Node.js as a Web Server
Node.js can be used to create web servers that handle HTTP requests and responses. It uses a non-blocking, event-driven architecture, making it efficient for handling multiple client requests simultaneously.
createServer() Method
The createServer() method is used to create an HTTP server in Node.js. It is provided by the http module and takes a callback function with req and res objects. The server listens to client requests and sends responses accordingly.
http.createServer(function (req, res) {
// handle request and response
});
writeHead() Method
The writeHead() method sends HTTP response headers — specifying the status code and content type. It must be called before sending the response body.
res.writeHead(statusCode, { 'Content-Type': 'text/html' });
Example — 200 means successful response
res.writeHead(200, { 'Content-Type': 'text/html' });
Reading Query String
A query string contains data sent in the URL after ?. Node.js uses the url module to read query strings.
http://localhost:8080/?name=John&age=21
Code
var url = require('url');
var q = url.parse(req.url, true).query;
// q.name → "John"
// q.age → "21"
Splitting Query String
When using url.parse(req.url, true), Node.js automatically converts the query string into a key-value object.
var qdata = url.parse(req.url, true).query;
// Input: name=Faizan&age=20
// Result:
{
name: "Faizan",
age: "20"
}
createServer() to handle requests, writeHead() to send responses, and the url module to read and split query strings efficiently.
File System (fs) Module in Node.js
The fs module stands for File System. It is a built-in tool in Node.js that allows you to work with files on your computer. Since it is built-in, you don't need to install anything — just require it.
Common Uses of the fs Module
Reading a File — fs.readFile()
Used to get the content out of a file to display it or use it. 'utf8' tells Node.js to read the file as human-readable text.
var fs = require('fs');
fs.readFile('message.txt', 'utf8', function(err, data) {
if (err) throw err;
console.log(data); // Prints the file content
});
Creating / Writing a File — fs.writeFile()
Creates a new file. If the file already exists, it replaces the old content with the new content.
var fs = require('fs');
fs.writeFile('mynewfile.txt', 'Hello students!', function (err) {
if (err) throw err;
console.log('File Created!');
});
Appending to a File — fs.appendFile()
Adds new content at the end of an existing file without deleting the old content.
fs.appendFile('mynewfile.txt', ' This is extra text.', function (err) {
if (err) throw err;
console.log('Updated!');
});
Deleting and Renaming Files
fs.unlink('filetodelete.txt', callback);fs.rename('old.txt', 'new.txt', callback);fs module provides methods to read, write, append, delete, and rename files asynchronously, making all file operations fast and non-blocking in Node.js.