Node.
js
Topics to be covered...
• What is Node.js?
• Why Node.js?
• Node.js - Pros & Cons
• Node.js Modules
• Node.js - Web Server
What is Node.js?
• Node.js 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
• Node.js allows you to run JavaScript code on the server, not just in the browser
Key Features
• Non-blocking and Asynchronous: Node.js is designed to handle many
connections simultaneously without waiting for responses to complete. It's highly
efficient for I/O-heavy applications.
• Single-Threaded: Node.js operates on a single-threaded event loop, which
handles all asynchronous I/O operations, making it lightweight and efficient.
• Vast Ecosystem: Node.js 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 Node.js?
• Highly Scalable: Node.js 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: Node.js 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: Node.js is often used for build tools like Grunt, Gulp, and Webpack,
enhancing the development workfl
Node.js - Pros & Cons
Pros
• High Performance: Node.js 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: Node.js 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: Node.js 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: Node.js has a vast ecosystem of packages available through
npm, which saves development time.
• Cross-Platform: Node.js is cross-platform and can be run on various operating
systems.
Node.js - 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: Node.js 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 Node.js ecosystem.
Node.js - 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.
• Node.js follows the CommonJS module system, which allows you to create, import,
and use modules in your applications.
Node.js - Modules
In Node.js, 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
Node.js - Modules
Core Modules
• These are built-in modules provided by Node.js, 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.
Node.js - Modules
Built-in Modules
• These are modules that come with Node.js 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.
Node.js - 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').
Node.js - 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.
Node.js - Modules
CommonJS vs. ES6 Modules
• Node.js primarily uses the CommonJS module system, which uses require and
module.exports.
• However, Node.js also supports ES6 modules using import and export
statements. This is useful when working with modern JavaScript and TypeScript.
Node.js - Modules
Console Module
// Display String on console
console.log("Hello, World!");
// String interpolation with template literals:
const empname = "Alice";
console.log(`Hello, ${empname}!`);
Node.js - Modules
Console Module
// Typically used for error message - similar to console.log()
console.error("This is an error message.");
// Used to print warning messages
console.warn("This is a warning message.");
// Used for informational messages
console.info("This is an informational message.");
// Used for debugging information - not available by-default in all envoronment
console.debug("Debugging information.");
Node.js - 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 }
];
console.table(data, ["name", "age"]);
// Clear the console
console.clear();
Node.js - fs (Filesystem) Modules
Read file
const fs = require('fs');
try {
const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
console.log('Reading file...\n');
Node.js - fs (Filesystem) Modules
Read File
const abc = require('fs');
abc.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
console.log('Reading file...');
Node.js - fs (Filesystem) Modules
Write File
const fs = require('fs');
const data = 'This is some data to write to the file.';
try {
fs.writeFileSync('output.txt', data);
console.log('File written successfully!');
} catch (err) {
console.error(err);
}
Node.js - fs (Filesystem) Modules
Write File
const wf = require('fs');
const dataToWrite = 'This is Write into a file with callback function.';
wf.writeFile('op.txt', dataToWrite, (err) => {
if (err) {
console.error(err);
return;
}
console.log('Operation successfull!');
});
Node.js - fs (Filesystem) Modules
List File
const fs = require('fs');
fs.readdir('.', (err, files) => {
if (err) {
console.error(err);
return;
}
console.log('Files in the current directory:');
files.forEach((file) => {
console.log(file);
});
});
Node.js - fs (Filesystem) Modules
File Exist or not
const ds = require('fs');
if (ds.existsSync('new.txt')) {
console.log('File exists');
} else {
console.log('File NEW.TXT does not exist');
}
Node.js - fs (Filesystem) Modules
Create Directory
const fs = require('fs');
fs.mkdir('NewDir', (err) => {
if (err) {
console.error(err);
return;
}
console.log('Directory created successfully');
});
Node.js - OS Modules
const os = require('os');
//Returns host name
const hostname = os.hostname();
console.log(`Hostname: ${hostname}`);
//Return platform
const platform = os.platform();
console.log(`Platform: ${platform}`);
//Return Architecture
const architecture = os.arch();
console.log(`Architecture: ${architecture}`);
Node.js - OS Modules
const os = require('os');
//Return CPU information
const cpus = os.cpus();
console.log('CPU Information:');
cpus.forEach((cpu, index) => {
console.log(`CPU ${index + 1}:`);
console.log(` Model: ${cpu.model}`);
console.log(` Speed: ${cpu.speed} MHz`);
});
Node.js - OS Modules
const os = require('os');
//Return Total & Free memory
const totalMemory = os.totalmem();
const freeMemory = os.freemem();
console.log(`Total Memory: ${totalMemory} bytes`);
console.log(`Free Memory: ${freeMemory} bytes`);
Node.js - OS Modules
const os = require('os');
//Return Network Interfaces
const networkInterfaces = os.networkInterfaces();
console.log('Network Interfaces:');
console.log(networkInterfaces);
//Return User Info
const userInfo = os.userInfo();
console.log('User Information:');
console.log(userInfo);
Node.js - PATH Modules
const path = require('path');
// Fullpath by joining directories and file name
const folder = '/Volumes/U/node_tut/coremodules/pathmodule';
const filename = 'example.txt';
const fullPath = path.join(folder, filename);
console.log(fullPath);
Node.js - PATH Modules
const path = require('path');
// Extract file extension from path
const fileExtension = path.extname(fullPath);
console.log(fileExtension);
// Normalizes a path by resolving '..' and '.' segments.
const messyPath =
'/Volumes/U/node_tut/../coremodules/pathmodule/./example.txt';
const normalizedPath = path.normalize(messyPath);
console.log("Normalized Path = "+ normalizedPath);
Node.js - Custom Modules
// File name: math.js
exports.add = function (x, y) {
return x + y;
};
exports.sub = function (x, y) {
return x - y;
};
exports.mult = function (x, y) {
return x * y;
};
exports.div = function (x, y) {
return x / y;
};
Node.js - Custom Modules
// File name: App.js
const calculator = require('./math');
let x = 50, y = 20;
console.log("Addition of 50 and 20 is "
+ calculator.add(x, y));
console.log("Subtraction of 50 and 20 is "
+ calculator.sub(x, y));
console.log("Multiplication of 50 and 20 is "
+ calculator.mult(x, y));
console.log("Division of 50 and 20 is "
+ calculator.div(x, y));
?