Node - Js For EveryOne
Node - Js For EveryOne
1
Node.js Page | 1
Contents
Introduction to Node.js ..............................................................................................................................................4
What is Node.js?................................................................................................................................................................. 4
What is npm? ...................................................................................................................................................................... 4
Installing Node.js and npm ................................................................................................................................................ 4
Verify the Installation......................................................................................................................................................... 4
Node.js REPL ....................................................................................................................................................................... 4
Visual Studio Code (VS Code) ............................................................................................................................................. 4
First Project (Hello World) ................................................................................................................................................. 5
Modules in Node.js ....................................................................................................................................................6
Core (built-in) modules ...................................................................................................................................................... 6
Local (custom) modules ..................................................................................................................................................... 6
Third-party modules (using npm) ...................................................................................................................................... 6
Common core modules ..............................................................................................................................................7
FS (File System) ................................................................................................................................................................... 7
Read a file ....................................................................................................................................................................... 7
Write a file ...................................................................................................................................................................... 7
Append data ................................................................................................................................................................... 7
Buffers............................................................................................................................................................................. 8
Create a Buffer ............................................................................................................................................................ 8
Read and Write to a Buffer......................................................................................................................................... 8
Manipulate a Buffer.................................................................................................................................................... 8
Buffer Methods........................................................................................................................................................... 9
Streams ......................................................................................................................................................................... 10
Readable Streams ..................................................................................................................................................... 10
Writable Streams ...................................................................................................................................................... 11
Duplex Streams......................................................................................................................................................... 11
Transform Streams ................................................................................................................................................... 12
Piping Streams .......................................................................................................................................................... 12
Delete a file................................................................................................................................................................... 13
Create and delete a directory ...................................................................................................................................... 13
Read the files of the directory ..................................................................................................................................... 13
Check Status (file or directory) .................................................................................................................................... 13
Path ................................................................................................................................................................................... 15
Get the last part of a path (the filename) ................................................................................................................... 15
Get the directory name of a path ................................................................................................................................ 15
Get the file extension of a path ................................................................................................................................... 15
Node.js Page | 2
Introduction to Node.js
What is Node.js?
Node.js is an open-source, cross-platform JavaScript runtime environment. It allows you to run JavaScript code on the
server-side, outside of a web browser. Node.js uses the V8 JavaScript engine (the same engine used by Google Chrome)
to execute code.
Node.js is designed to be asynchronous and non-blocking. This means it can handle multiple operations at the same
time without waiting for one to finish before starting another. This is achieved through event-driven architecture.
What is npm?
npm stands for Node Package Manager. It is a package manager for JavaScript and is the default package manager for
Node.js. npm allows you to install, share, and manage code packages written in JavaScript. These packages can be
libraries, tools, or frameworks that you can use in your Node.js projects.
Note: The Node.js installer includes npm (Node Package Manager). When you install Node.js, npm is automatically
installed as well.
run node -v and npm -v to check the installed versions of Node.js and npm.
Input Output
node -v v20.13.1
npm -v 10.5.2
Node.js REPL
REPL stands for Read-Eval-Print Loop. It's an interactive shell that allows you to execute JavaScript code one line at a
time.
For start the REPL open your terminal. Type node and press Enter. You should see a prompt (>) where you can start
typing JavaScript code.
console.log("Hello, Node.js!");
node hello.js
Note: The node command is used to run Node.js scripts. It allows you to execute JavaScript code outside of a web
browser, directly in your operating system's terminal or command prompt.
Node.js Page | 6
Modules in Node.js
Modules are reusable pieces of code that you can use to organize your Node.js applications. They help you break down
your application into smaller, manageable parts, making your code more modular, maintainable, and reusable.
In Node.js, there are three types of modules:
• Core (built-in) modules,
• Local (custom) modules,
• Third-party modules.
1. fs (file system):
allows you to interact with the file system on your computer. It provides functions to read, write, delete, and
manipulate files and directories.
2. path:
The path module in Node.js provides utilities for working with file and directory paths.
3. http:
The http module in Node.js allows you to create an HTTP server that can handle requests and send responses
(create and manage HTTP servers and clients).
4. os:
The os module in Node.js provides several operating system-related utility methods. It allows you to interact
with the operating system to retrieve information like the system's hostname, platform, memory usage, and
more.
//Create a file named math.js: //Use the custom module in another file:
// math.js // app.js
function add(a, b) { const math = require("./math");
return a + b;
} const sum = math.add(5, 3);
function subtract(a, b) { const difference = math.subtract(5, 3);
return a - b;
} console.log(`Sum: ${sum}`); // Sum: 8
module.exports = { console.log(`Difference: ${difference}`); // Difference: 2
add,
subtract,
};
Read a file
You can read files using various methods provided by the fs module. The callback function receives two arguments: an
error object (if an error occurred) and the file content. readFileSync is the synchronous version of readFile. It blocks the
event loop until the file is read.
Write a file
You can write to files using the fs module. The callback function receives an error object if an error occurred.
writeFileSync is the synchronous version of writeFile. It blocks the event loop until the file is written.
Append data
You can append data to an existing file using fs.appendFile or fs.appendFileSync.
//Asynchronous Appending data to an existing file //Synchronous Appending data to an existing file
const content = " This is appended text."; const content = " This is appended text.";
fs.appendFile("example.txt", content, "utf8", (err) => {
if (err) { try {
console.error("Error appending file:", err); fs.appendFileSync("example.txt", content, "utf8");
return; console.log("Content appended");
} } catch (err) {
console.log("Content appended"); console.error("Error appending file:", err);
}); }
Node.js Page | 8
Buffers
Buffers in Node.js are a way to handle binary data directly. They are particularly useful when working with streams, file
systems, or network communications where data is often received or sent in raw binary format.
What is a Buffer?
A buffer is a temporary storage area for binary data. In Node.js, the Buffer class is a global type for dealing with binary
data directly.
Buffers are like arrays of integers but correspond to raw memory allocations outside the V8 heap. Each element in a
buffer is an 8-bit integer. Buffers are used to handle raw binary data that might come from a file, network, or other
streams.
Create a Buffer
1. From a String: each character is converted to its binary equivalent.
const buffer = Buffer.alloc(10); // Create a buffer of length 10, initialized with zeros
console.log(buffer);
// Output: <Buffer 00 00 00 00 00 00 00 00 00 00>
Manipulate a Buffer
Buffer Methods
1. Buffer.byteLength(): Returns the length of the buffer in bytes.
Streams
Streams are a fundamental concept in Node.js for handling I/O operations efficiently. They allow you to read or write
data sequentially in small chunks, rather than loading all data into memory at once. This makes streams particularly
useful for working with large files or data from network sources.
Types of Streams
1. Readable Streams: Used for reading data in chunks.
2. Writable Streams: Used for writing data in chunks.
3. Duplex Streams: Can read and write data.
4. Transform Streams: A type of duplex stream where the output is computed based on the input.
5. Piping: Directly transfers data from one stream to another.
Streams allow efficient handling of data, especially for large amounts of data, by processing it in chunks and keeping
memory usage low.
Readable Streams
Readable streams are used to read data. Examples include reading data from a file, an HTTP request.
const fs = require("fs");
Writable Streams
Writable streams are used to write data. Examples include writing data to a file or sending data in an HTTP response.
const fs = require("fs");
Duplex Streams
Duplex streams are both readable and writable. Examples include TCP sockets and zlib streams for compression.
const net = require("net");
server.listen(8080, () => {
console.log("Server listening on port 8080");
});
Node.js Page | 12
Transform Streams
Transform streams are a type of duplex stream where the output is computed based on the input. A common example is
compression/decompression or encryption/decryption.
const fs = require("fs");
const zlib = require("zlib");
// Pipe the readable stream into the gzip stream and then into the writable stream
readableStream.pipe(gzip).pipe(writableStream);
Piping Streams
Piping is a mechanism to connect the output of one stream directly to the input of another stream. This is commonly
used for streaming data from a readable stream to a writable stream.
const fs = require("fs");
writableStream.on("finish", () => {
console.log("Piping complete.");
});
Node.js Page | 13
Delete a file
You can delete files using fs.unlink or fs.unlinkSync.
//Asynchronous File Delete //Synchronous File Delete
// Checking Directory Status and Contents // Checking Directory Status and Contents Synchronously
Asynchronously
try {
fs.stat('myDirectory', (err, stats) => { const stats = fs.statSync("myDirectory");
if (err) {
console.error('Error getting directory stats:', err); if (stats.isDirectory()) {
return; console.log("This is a directory");
} const files = fs.readdirSync("myDirectory");
console.log("Directory contents:", files);
if (stats.isDirectory()) { } else {
console.log('This is a directory'); console.log("This is not a directory");
fs.readdir('myDirectory', (err, files) => { }
if (err) { } catch (err) {
console.error('Error reading directory:', err); console.error("Error getting directory stats:", err);
return; }
}
console.log('Directory contents:', files);
});
} else {
console.log('This is not a directory');
}
Node.js Page | 15
Path
The path module in Node.js provides utilities for working with file and directory paths. First, you need to import the path
module:
const path = require("path");
The path.normalize() method is useful for cleaning up paths by resolving ".." and "." segments and reducing multiple
slashes to a single slash. This ensures that paths are consistent and easier to work with. For example,
• /home/user/.. moves up one directory to /home.
• /projects/./ becomes /projects/ (current directory . is removed).
• project1/../ moves up one directory to projects.
• project2// is reduced to project2/.
Http
The http module in Node.js allows you to create an HTTP server that can handle requests and send responses (create
and manage HTTP servers and clients).
3. Make the Server Listen on a Specific Port: You need to specify the port and hostname for your server to listen to incoming
requests.
Different Routes
Routes define the endpoints (URLs) that your application responds to. Each route can be associated with a different
function, handling specific requests. In a basic Node.js HTTP server, routes determine what content or functionality is
provided when a user accesses a specific path.
In Node.js, routes are managed using the http module. Here's a deeper dive into how you can handle different routes.
1. Create the HTTP Server: As before, you start by creating an HTTP server.
2. Check the Request URL: Use req.url to determine the path that the client has requested.
3. Respond Based on the Path: Send different responses based on the requested path.
• HTTP Status Code: Indicates the result of the HTTP request. Common status codes include:
o 200 OK: The request was successful.
o 404 Not Found: The requested resource could not be found.
o 500 Internal Server Error: The server encountered an error.
• HTTP Headers: Provide metadata about the response. Important headers include:
o Content-Type: Specifies the media type of the resource. For HTML, it's text/html.
o Content-Length: Indicates the size of the response body in bytes.
• Response Body: The actual content that is returned to the client, which in this case is HTML code.
// Start the server and listen on the specified port and hostname
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
In brief Set the Content-Type to application/json, convert JavaScript objects to JSON strings using JSON.stringify, and send the JSON
string as the response.
Node.js Page | 22
"Collect data chunks" and "Process the complete data" are two sequential steps in handling incoming data in a Node.js
server. First, during the "Collect data chunks" step, the server listens for data events, accumulating the small pieces of
incoming data into a single string. This step ensures all parts of the data are gathered. Once all data chunks are received,
the "Process the complete data" step begins, triggered by the end event. Here, the complete data string is processed,
typically by parsing it from JSON format into a JavaScript object. The order is crucial: you must collect all chunks before
you can accurately process the complete data. The purpose of collecting chunks is to ensure you have the full data set
before converting or using it, ensuring data integrity and accurate processing.
req.on("end", () => {
try {
const parsedData = JSON.parse(body);
// Now you can use parsedData
} catch (error) {
// Handle JSON parsing error
}
});
Here’s a full example demonstrating both steps together in a Node.js server handling JSON data from a POST request:
By separating these two steps, you ensure that you handle incoming data correctly and efficiently in your Node.js server.
Node.js Page | 24
OS
The os module in Node.js provides several operating system-related utility methods. It allows you to interact with the
operating system to retrieve information like the system's hostname, platform, memory usage, and more. You need to
import the os module using the Require function.
const os = require("os");
console.log(`Platform: ${os.platform()}`); // Output: 'win32', 'linux', 'darwin', etc.
const os = require("os");
console.log(`Architecture: ${os.arch()}`); // Output: 'x64', 'arm', 'ia32', etc.
const os = require("os");
console.log(`Hostname: ${os.hostname()}`); // Output: Hostname of the machine
const os = require("os");
console.log(`Network Interfaces: ${JSON.stringify(os.networkInterfaces(), null, 2)}`);
const os = require("os");
console.log(`Total Memory: ${os.totalmem() / (1024 * 1024)} MB`); // Output in Megabytes
const os = require("os");
console.log(`Free Memory: ${os.freemem() / (1024 * 1024)} MB`); // Output in Megabytes
const os = require("os");
console.log(`System Uptime: ${os.uptime()} seconds`);
Node.js Page | 25
const os = require("os");
console.log(`User Info: ${JSON.stringify(os.userInfo(), null, 2)}`);
const os = require("os");
console.log(`Home Directory: ${os.homedir()}`);
const os = require("os");
console.log(`Temporary Directory: ${os.tmpdir()}`);
Node.js Page | 26
Event-Driven Programming
In Node.js, much of the programming involves handling events. Event-driven programming is a programming paradigm in
which the flow of the program is determined by events such as user actions (mouse clicks, key presses), sensor outputs,
or messages from other programs/threads. In Node.js, this paradigm is essential due to its asynchronous nature.
Event Loop
The event loop is the core of Node.js's asynchronous behavior. It allows Node.js to perform non-blocking I/O operations
by offloading operations to the system kernel whenever possible. The event loop is a key concept in Node.js that allows it
to handle multiple operations concurrently without getting stuck. It works like a manager who keeps track of tasks and
makes sure they are done in the right order.
console.log("Start"); //Output
console.log("End");
The event loop allows Node.js to handle multiple tasks efficiently without waiting for each task to complete before
starting the next one. This makes Node.js great for building fast and responsive applications.
Node.js Page | 27
EventEmitter Class
The EventEmitter class is at the core of Node.js's event-driven architecture. It provides a way to emit and listen to
events. For using it first, you need to include the events module.
Emit an Event
Emitting an event means triggering or signaling that an event has occurred. When you emit an event, you tell the
EventEmitter instance to execute all the callback functions that are registered to listen for that specific event. Trigger an
event using emit(). This signals that something has happened and calls all the listeners for that event.
Listen to an Event
Listening to an event means registering a callback function (listener) that will be executed when a specific event is
emitted. Register a callback function for an event using on(). This function will be executed whenever the specified event
is emitted.
// Listen to an event
myEmitter.on("alwaysGreet", () => {
console.log("Hello, this event will always be handled.");
});
Callbacks
A callback is a function that is passed to another function as an argument and is executed after some operation has
been completed. In Node.js, callbacks are used extensively to handle asynchronous operations, allowing your program
to continue running while waiting for the operation to be completed. By using callbacks, Node.js can perform non-
blocking operations, allowing your applications to be efficient and responsive.
const fs = require("fs");
readFileSync(); //output :Error reading file: Error reading file: ENOENT: no such file or directory...
In the above example, the readFileSync function tries to read a non-existent file. If an error occurs, it is caught by the
catch block, and an error message is printed to the console.
Node.js Page | 31
const fs = require("fs");
readFileAsync();
Node.js Page | 32
readFileAsync();