Node.
js
Topics to be covered...
• What is [Link]?
• Why [Link]?
• [Link] - Pros & Cons
• [Link] Modules
• [Link] - Web Server
What is [Link]?
• [Link] is an open-source, cross-platform JavaScript runtime environment that
executes JavaScript code server-side
• It's built on the V8 JavaScript engine from Google, which is also used in Google
Chrome
• [Link] allows you to run JavaScript code on the server, not just in the browser
Key Features
• Non-blocking and Asynchronous: [Link] is designed to handle many
connections simultaneously without waiting for responses to complete. It's highly
efficient for I/O-heavy applications.
• Single-Threaded: [Link] operates on a single-threaded event loop, which
handles all asynchronous I/O operations, making it lightweight and efficient.
• Vast Ecosystem: [Link] has a rich ecosystem of libraries and packages
available through the npm (Node Package Manager) repository.
• Real-time Applications: It's well-suited for building real-time applications like
chat applications, online gaming, and collaboration tools.
Why [Link]?
• Highly Scalable: [Link] is designed for building scalable network applications,
making it suitable for large-scale systems.
• Real-time Applications: It's ideal for building real-time applications, such as
chat applications, online gaming, and live streaming.
• Microservices: [Link] is well-suited for building microservices-based
architectures due to its lightweight nature and ease of communication between
services.
• API Servers: It's commonly used to create RESTful APIs and GraphQL servers,
facilitating data communication between client and server.
• Build Tools: [Link] is often used for build tools like Grunt, Gulp, and Webpack,
enhancing the development workfl
[Link] - Pros & Cons
Pros
• High Performance: [Link] is known for its speed and efficiency in handling
concurrent connections, making it faster than traditional server-side languages.
• JavaScript Everywhere: Developers can use JavaScript on both the client and
server sides, reducing the need to switch between languages.
• Active Community: [Link] has a vibrant and active community, which means
there's a wealth of resources, packages, and support available.
• npm Ecosystem: npm provides access to thousands of packages and libraries,
simplifying development tasks.
• Fast Execution: [Link] is known for its speed and non-blocking architecture,
making it suitable for high-performance applications.
• Scalability: It can handle a large number of concurrent connections efficiently,
making it a good choice for scalable applications.
• Rich Ecosystem: [Link] has a vast ecosystem of packages available through
npm, which saves development time.
• Cross-Platform: [Link] is cross-platform and can be run on various operating
systems.
[Link] - Pros & Cons
Cons
• Single-Threaded: While the event loop is efficient, it's still single-threaded, which means
CPU-bound tasks can block the event loop.
• Callback Hell: Asynchronous code can lead to callback hell, where deeply nested
callbacks make the code hard to read and maintain. However, this can be mitigated with
modern JavaScript features and libraries.
• Not Ideal for CPU-Intensive Tasks: [Link] is not well-suited for CPU-intensive tasks
as it can block the event loop and lead to reduced performance.
• Immaturity for Some Use Cases: It may not be the best choice for certain use cases,
such as heavy data processing or when specific libraries are required that are not available in
the [Link] ecosystem.
[Link] - Modules
• A module is a reusable block of code that encapsulates related functions and
variables.
• Modules help in organizing and structuring your code, making it more maintainable
and scalable.
• [Link] follows the CommonJS module system, which allows you to create, import,
and use modules in your applications.
[Link] - Modules
In [Link], there are several types of modules, each serving a different purpose and
having its own way of defining and using modules.
• Core Modules
• Built-in Modules
• Local Modules
• Third Party Modules
[Link] - Modules
Core Modules
• These are built-in modules provided by [Link], such as fs (file system), http
(HTTP server/client), path (path manipulation), and os (operating system
information).
• Core modules can be imported using require('module_name') without the
need for installation.
[Link] - Modules
Built-in Modules
• These are modules that come with [Link] but are not part of the CommonJS
standard.
• They are included by default without the need for using require.
• Examples include global, process, and console.
[Link] - Modules
Local Modules
• Local modules are modules you create in your project.
• They are also known as custom or user-defined modules.
• You define and export functions, variables, or classes in your JavaScript files, and
then you can import and use them in other files using require('./module_file_path').
[Link] - Modules
Third Party Modules
• These modules are created by third-party developers and are available via the
Node Package Manager (NPM).
• You can install third-party modules using npm install module_name, and then you
can import and use them in your application.
[Link] - Modules
CommonJS vs. ES6 Modules
• [Link] primarily uses the CommonJS module system, which uses require and
[Link].
• However, [Link] also supports ES6 modules using import and export
statements. This is useful when working with modern JavaScript and TypeScript.
[Link] - Modules
Console Module
// Display String on console
[Link]("Hello, World!");
// String interpolation with template literals:
const empname = "Alice";
[Link](`Hello, ${empname}!`);
[Link] - Modules
Console Module
// Typically used for error message - similar to [Link]()
[Link]("This is an error message.");
// Used to print warning messages
[Link]("This is a warning message.");
// Used for informational messages
[Link]("This is an informational message.");
// Used for debugging information - not available by-default in all envoronment
[Link]("Debugging information.");
[Link] - Modules
Console Module
// Prints a tabular representation of data, which can be an array of objects.
// You can specify which properties to display in the table.
const data = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
{ name: "Charlie", age: 35 }
];
[Link](data, ["name", "age"]);
// Clear the console
[Link]();
[Link] - fs (Filesystem) Modules
Read file
const fs = require('fs');
try {
const data = [Link]('[Link]', 'utf8');
[Link](data);
} catch (err) {
[Link](err);
}
[Link]('Reading file...\n');
[Link] - fs (Filesystem) Modules
Read File
const abc = require('fs');
[Link]('[Link]', 'utf8', (err, data) => {
if (err) {
[Link](err);
return;
}
[Link](data);
});
[Link]('Reading file...');
[Link] - fs (Filesystem) Modules
Write File
const fs = require('fs');
const data = 'This is some data to write to the file.';
try {
[Link]('[Link]', data);
[Link]('File written successfully!');
} catch (err) {
[Link](err);
}
[Link] - fs (Filesystem) Modules
Write File
const wf = require('fs');
const dataToWrite = 'This is Write into a file with callback function.';
[Link]('[Link]', dataToWrite, (err) => {
if (err) {
[Link](err);
return;
}
[Link]('Operation successfull!');
});
[Link] - fs (Filesystem) Modules
List File
const fs = require('fs');
[Link]('.', (err, files) => {
if (err) {
[Link](err);
return;
}
[Link]('Files in the current directory:');
[Link]((file) => {
[Link](file);
});
});
[Link] - fs (Filesystem) Modules
File Exist or not
const ds = require('fs');
if ([Link]('[Link]')) {
[Link]('File exists');
} else {
[Link]('File [Link] does not exist');
}
[Link] - fs (Filesystem) Modules
Create Directory
const fs = require('fs');
[Link]('NewDir', (err) => {
if (err) {
[Link](err);
return;
}
[Link]('Directory created successfully');
});
[Link] - OS Modules
const os = require('os');
//Returns host name
const hostname = [Link]();
[Link](`Hostname: ${hostname}`);
//Return platform
const platform = [Link]();
[Link](`Platform: ${platform}`);
//Return Architecture
const architecture = [Link]();
[Link](`Architecture: ${architecture}`);
[Link] - OS Modules
const os = require('os');
//Return CPU information
const cpus = [Link]();
[Link]('CPU Information:');
[Link]((cpu, index) => {
[Link](`CPU ${index + 1}:`);
[Link](` Model: ${[Link]}`);
[Link](` Speed: ${[Link]} MHz`);
});
[Link] - OS Modules
const os = require('os');
//Return Total & Free memory
const totalMemory = [Link]();
const freeMemory = [Link]();
[Link](`Total Memory: ${totalMemory} bytes`);
[Link](`Free Memory: ${freeMemory} bytes`);
[Link] - OS Modules
const os = require('os');
//Return Network Interfaces
const networkInterfaces = [Link]();
[Link]('Network Interfaces:');
[Link](networkInterfaces);
//Return User Info
const userInfo = [Link]();
[Link]('User Information:');
[Link](userInfo);
[Link] - PATH Modules
const path = require('path');
// Fullpath by joining directories and file name
const folder = '/Volumes/U/node_tut/coremodules/pathmodule';
const filename = '[Link]';
const fullPath = [Link](folder, filename);
[Link](fullPath);
[Link] - PATH Modules
const path = require('path');
// Extract file extension from path
const fileExtension = [Link](fullPath);
[Link](fileExtension);
// Normalizes a path by resolving '..' and '.' segments.
const messyPath =
'/Volumes/U/node_tut/../coremodules/pathmodule/./[Link]';
const normalizedPath = [Link](messyPath);
[Link]("Normalized Path = "+ normalizedPath);
[Link] - Custom Modules
// File name: [Link]
[Link] = function (x, y) {
return x + y;
};
[Link] = function (x, y) {
return x - y;
};
[Link] = function (x, y) {
return x * y;
};
[Link] = function (x, y) {
return x / y;
};
[Link] - Custom Modules
// File name: [Link]
const calculator = require('./math');
let x = 50, y = 20;
[Link]("Addition of 50 and 20 is "
+ [Link](x, y));
[Link]("Subtraction of 50 and 20 is "
+ [Link](x, y));
[Link]("Multiplication of 50 and 20 is "
+ [Link](x, y));
[Link]("Division of 50 and 20 is "
+ [Link](x, y));
?