In recent years, Node.js has gained immense popularity among developers for building high-performance and scalable web applications. Powered by Chrome's V8 JavaScript engine, Node.js allows developers to use JavaScript on both the client and server sides, providing a seamless and consistent development experience. we will explore the key features and benefits of Node.js and delve into why it has become a top choice for building modern web applications.
Node.js is a runtime environment that enables server-side JavaScript execution. It utilizes an event-driven, non-blocking I/O model, which allows it to handle a large number of concurrent requests efficiently. This non-blocking I/O model, along with its single-threaded architecture, makes Node.js highly scalable and capable of handling real-time applications.
Install Node.js by visiting the official Node.js website (https://nodejs.org) and downloading the appropriate installer for your operating system. Run the installer and follow the on-screen instructions to complete the installation. Verify the installation by opening a command prompt or terminal window and running node -v and npm -v to check the installed versions of Node.js and npm, respectively.
Create a new directory for your Node.js project. Open a command prompt or terminal and navigate to the project directory using the cd command.
In the project directory, run the following command to initialize a new Node.js project:
npm init
Follow the prompts to provide information about your project or press Enter to accept the default values.
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
Save the file and create an example.txt file in the same directory with some content.
Run the script using node fileSystem.js to read the file and display its content.
The http module provides an HTTP server and client implementation. Create a new file named httpServer.js and add the following code to create a basic HTTP server:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, Node.js!');
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
Save the file and run the script using node httpServer.js to start the server.
Visit http://localhost:3000/ in a web browser to see the server response.
The path module provides utilities for working with file and directory paths. Create a new file named pathModule.js and add the following code to join and resolve paths:
const path = require('path');
const path1 = '/path/to';
const path2 = 'file.txt';
const joinedPath = path.join(path1, path2);
console.log(`Joined Path: ${joinedPath}`);
const resolvedPath = path.resolve(__dirname, 'pathModule.js');
console.log(`Resolved Path: ${resolvedPath}`);
Save the file and run the script using node pathModule.js to see the joined and resolved paths.
const os = require('os');
console.log(`Platform: ${os.platform()}`);
console.log(`Architecture: ${os.arch()}`);
console.log(`Total Memory: ${os.totalmem() / 1024 / 1024} MB`);
console.log(`Free Memory: ${os.freemem() / 1024 / 1024} MB`);
Save the file and run the script using node osModule.js to see the operating system information.
The events module provides an event-driven programming paradigm in Node.js. Create a new file named eventsModule.js and add the following code to create and handle events:
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('customEvent', (arg) => {
console.log(`Event fired with argument: ${arg}`);
});
myEmitter.emit('customEvent', 'Hello, Events!');
Save the file and run the script using node eventsModule.js to see the event being emitted and handled.
The crypto module provides cryptographic functionalities in Node.js. Create a new file named cryptoModule.js and add the following code to generate a hash using the crypto module:
const crypto = require('crypto');
const data = 'Hello, Crypto!';
const hash = crypto.createHash('sha256').update(data).digest('hex');
console.log(`Hash: ${hash}`);
Save the file and run the script using node cryptoModule.js to see the generated hash.
The stream module provides an interface for working with streaming data. Create a new file named streamModule.js and add the following code to create a writable stream and write data to a file:
const fs = require('fs');
const writableStream = fs.createWriteStream('output.txt');
writableStream.write('Hello, Stream!');
writableStream.end();
Save the file and run the script using node streamModule.js to write data to the output.txt file.
The util module provides utility functions in Node.js. Create a new file named utilModule.js and add the following code to use the util module:
const util = require('util');
const name = 'John';
const age = 30;
const greeting = util.format('Hello, %s! You are %d years old.', name, age);
console.log(greeting);
Save the file and run the script using node utilModule.js to see the formatted greeting.
The cluster module allows you to create child processes to take advantage of multi-core systems. Create a new file named clusterModule.js and add the following code to demonstrate using the cluster module:
const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
console.log(`Master process ID: ${process.pid}`);
// Fork workers
for (let i = 0; i < os.cpus().length; i++) {
cluster.fork();
}
} else {
console.log(`Worker process ID: ${process.pid}`);
}
We have to access a MongoDB database with Node.js. For download and install the official MongoDB driver, using Command Terminal and run the following:
C:\Users\Your Name>npm install mongodb
const { MongoClient, ServerApiVersion } = require("mongodb");
//const uri = "mongodb://localhost:27017/";
const uri = "mongodb://127.0.0.1:27017/";
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
}
);
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
await client.db("admin").command({ ping: 1 });
console.log("Pinged your deployment. You successfully connected to MongoDB!");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
We have to access a emailer with Node.js. For download and install the node js emailer , using Command Terminal and run the following:
C:\Users\Your Name>npm install nodemailer
and use below code for send email just import nodemailer and use their createTransport and sendMail function
let emailer = require('nodemailer');
let transeservice = emailer.createTransport({
service: 'gmail',
auth: {
user: 'anygmailemailthatyouhave@gmail.com',
pass: 'passwordofthisemail'
}
});
let mailOptions = {
from: 'sameemailthatuseforauth@gmail.com',
to: 'anyemail@gmail.com',
subject: 'your email subject',
text: 'Enjoy the email from nodejs!'
};
transeservice.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
The objective of this website is to Train the people in software field, develop them as good human resources and deploy them in meaningful employment. The high level of hands-on-training and case studies ensures that Trainee gain the optimum benefits. Online Tutorial on Technology subjects as below with Interview Questions and Answers.