What is NodeJS?
NodeJS is an open-source, cross-platform JavaScript runtime environment that allows you to execute JavaScript code outside of a web browser.
NodeJS is primarily used for server-side scripting, where JavaScript is used to produce dynamic web content before the page is sent to the user's web browser.
-
Key Features:
- Event-Driven Architecture: NodeJS uses an event-driven, non-blocking I/O model, making it efficient and lightweight.
- Single-Threaded: Although single-threaded, NodeJS handles concurrent operations using its asynchronous nature and the event loop.
- Built on V8: NodeJS is built on Google Chrome's V8 JavaScript engine, making it extremely fast in executing JavaScript code.
How Does NodeJS Work in the Background?
Event Loop
- NodeJS operates on a single-threaded event loop, which allows it to handle multiple concurrent requests without blocking the thread.
- Phases of Event Loop:
-
Timers: Executes callbacks scheduled by
setTimeout()
andsetInterval()
. - Pending Callbacks: Executes I/O callbacks deferred to the next loop iteration.
- Idle, Prepare: Used internally by NodeJS.
- Poll: Retrieves new I/O events and executes I/O-related callbacks.
-
Check: Executes callbacks scheduled by
setImmediate()
. -
Close Callbacks: Executes
close
event callbacks.
Non-blocking I/O
NodeJS handles I/O operations asynchronously, meaning it doesn’t wait for operations to complete before moving on to the next task.
Example:
const fs = require('fs');
console.log("Start");
// Reading a file asynchronously
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
console.log("End");
Output:
Start
End
(contents of example.txt)
Explanation: NodeJS continues to execute the code after the fs.readFile()
function is called, without waiting for the file to be read. This demonstrates its non-blocking I/O model.
What are Modules in NodeJS?
Modules are blocks of encapsulated code that communicate with an external application based on their related functionality.
-
Types of Modules:
-
Core Modules: Built into NodeJS (e.g.,
fs
,http
,path
, etc.). - Local Modules: Created by users to organize and structure code.
-
Third-Party Modules: Installed via npm (e.g.,
express
,lodash
).
-
Core Modules: Built into NodeJS (e.g.,
Ways of Importing and Exporting Modules in JavaScript and NodeJS
In JavaScript (ES6 Modules):
- Exporting:
// Named export
export const add = (a, b) => a + b;
// Default export
export default function subtract(a, b) {
return a - b;
}
- Importing:
// Named import
import { add } from './math.js';
// Default import
import subtract from './math.js';
In NodeJS (CommonJS Modules):
- Exporting:
// Using module.exports
module.exports.add = (a, b) => a + b;
// Using exports shorthand
exports.subtract = (a, b) => a - b;
- Importing:
// Importing modules
const math = require('./math.js');
const add = math.add;
const subtract = math.subtract;
What is File Handling in NodeJS?
File handling in NodeJS allows you to work with the file system on your machine, including reading, writing, updating, and deleting files.
Important Functions:
-
Some of the most important
fs
Module Functions:-
fs.readFile()
: Asynchronously reads the contents of a file. -
fs.writeFile()
: Asynchronously writes data to a file, replacing the file if it already exists. -
fs.appendFile()
: Appends data to a file. If the file does not exist, it creates a new file. -
fs.unlink()
: Deletes a file. -
fs.rename()
: Renames a file.
-
Example:
const fs = require('fs');
// Writing to a file
fs.writeFile('example.txt', 'Hello, NodeJS!', (err) => {
if (err) throw err;
console.log('File written successfully.');
// Reading the file
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log('File contents:', data);
// Appending to the file
fs.appendFile('example.txt', ' This is an appended text.', (err) => {
if (err) throw err;
console.log('File appended successfully.');
// Renaming the file
fs.rename('example.txt', 'newExample.txt', (err) => {
if (err) throw err;
console.log('File renamed successfully.');
// Deleting the file
fs.unlink('newExample.txt', (err) => {
if (err) throw err;
console.log('File deleted successfully.');
});
});
});
});
});
Output:
File written successfully.
File contents: Hello, NodeJS!
File appended successfully.
File renamed successfully.
File deleted successfully.
How to Build a Server in NodeJS?
The http
module is a core module in NodeJS that allows you to create a server that listens for requests on a specific port and sends responses.
Example:
const http = require('http');
// Creating a server
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
// Listening on port 3000
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
Output:
Server running at http://127.0.0.1:3000/
Explanation: The server responds with "Hello, World!" every time it receives a request. The server listens on localhost
(127.0.0.1) at port 3000.
What is an HTTP Module?
The http
module in NodeJS provides functionalities to create HTTP servers and clients.
Important Functions?
-
Some of the most important functions of
HTTP
module are:-
http.createServer()
: Creates an HTTP server that listens to requests and sends responses. -
req.method
: Retrieves the request method (GET, POST, etc.). -
req.url
: Retrieves the URL of the request. -
res.writeHead()
: Sets the status code and headers for the response. -
res.end()
: Signals to the server that all of the response headers and body have been sent.
-
Example:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome to the homepage!\n');
} else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome to the about page!\n');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found\n');
}
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
Output:
- If you navigate to
http://127.0.0.1:3000/
, the server will display "Welcome to the homepage!". - If you navigate to
http://127.0.0.1:3000/about
, the server will display "Welcome to the about page!". - If you navigate to any other URL, the server will display "404 Not Found".
To learn about URLs, HTTP Methods, Express Framework, and Versioning, please click here.