Node.js is an open-source and cross-platform javascript library that allows you to use JavaScript to develop server-side applications.
Every web browser has a JavaScript engine that takes JavaScript code and compiles it to machine code. For example, Firefox uses SpiderMonkey, and Google Chrome uses V8. Because browsers use different JavaScript engines, sometimes, you will see that JavaScript behaves differently between browsers.
In 2009, Ryan Dahl, the creator of Node.js, took the V8 engine and embedded it in an application that could execute JavaScript on the server.
Unique Features of NODE JS:-
Node.js is Single-threaded
Node.js is single-threaded. It means that each process has only one thread of execution.
The single-threaded execution model allows Node.js to handle more concurrent requests easily via the event loop. Because of this, Node.js applications typically consume comparatively less memory.
If you have not familiar with the event loop, check out this event loop tutorial. The event loop in Node.js works the same as the event loop in web browsers.
Node.js uses Non-blocking I/O
I/O stands for input/output. It can be disk access, a network request, or a database connection. I/O requests are expensive and slow and hence block other operations.
Node.js addresses blocking I/O issues by using non-blocking I/O requests.
Non-blocking means that you can make a request while doing something else, and then, when this request is finished, a callback will execute to handle the result.
In other words, the program execution can continue while other operations are taking place.
How to Install Node JS:-
Just write the download node in google it provides LTS , and download according to your o/s.
To confirm the installation, you can open Command Prompt or Windows Terminal and type the following command:
node -v
Step to create First Hello World Program in Node JS:-
1) Create Folder
2) Open this folder in VS Code
3) Type npm init
4) create hello.js file
5) write following code
console.log("hello world")
6) open terminal write
node hello.js
What is Modules in NODE JS:-
It is similar to JS library, and it is used to contain predefine functionality under
NODE application.
We can create our own module also.
Node JS provide various modules, we will step all modules one by one
HTTP module in node js:-
This is the most important module to manage HttpRequest and HttpResonse.
Now I am creating one simple program to explain http module.
consthttp = require('http')
consthostname = '127.0.0.1'
constport = 3000
constserver = http.createServer((req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'text/html')
res.end('<h1>Hello World</h1>')
})
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})
Another Example of an HTTP Module:-
consthttp = require('http');
constport = 2000;
consthost = "127.0.0.1"
constserver = http.createServer((req,res)=>{
res.statusCode=200
varp = 120000
varr = 5.5
vart = 2
varsi = (p*r*t)/100
res.setHeader('Content-Type','text/html')
res.end(`<h1>Result is ${si} </h1>`)
})
server.listen(port,host,()=>{
console.log(`click to execute http://${host}:${port}`)
console.log(`Server running at http://${hostname}:${port}/`)
})
The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client. using this we can create web server to post node script under web environment.
Use the createServer() method to create an HTTP server.
Read the query String using Http Module:-
varhttp = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type':'text/html'});
res.write(req.url);
res.end();
}).listen(8080);
File Module in Node JS:-
This is another important module in Node Js that is used to manage file operation.
it provide following operation
1) Write File
2) Read File
3) Append File
4) Delete the File
Node JS provide fs module to perform file handling operation.
varfs = require('fs');
This operation must be implemented using asynchronous mode
Now I am explaining using example:-
varfs = require('fs');
fs.open('abc.txt', 'w', function (err, file) {
if (err) throwerr;
console.log('Saved!');
});
fs.writeFile('abc.txt', 'Hello content!', function (err) {
if (err) throwerr;
console.log('Saved!');
});
fs.readFile('abc.txt',(err, data) => {
vararray = data.toString().split(" ");
console.log(data.toString());
for(iinarray) {
// Printing the response array
console.log(array[i]);
}
})
fs.appendFile('abc.txt', ' dftrdyhtyt.', function (err) {
if (err) throwerr;
console.log('Updated!');
});
fs.unlink('abc.txt', function (err) {
if (err) throwerr;
console.log('File deleted!');
});
fs.rename('abc.txt', 'abcnew.txt', function (err) {
if (err) throwerr;
console.log('File Renamed!');
});
Task for Asynchronous Mode:
First Write then Read
First Read then write
First Append then Read
First Read then append
Create Marksheet program of 12th class student and display result based
console.log('Server running at http://127.0.0.1:1337/');
Event Module in JS:-
This is very simple module that is used to perform the action, we can attach event dynamically using this Event Module.
varevents=require('events');
vareventEmitter=newevents.EventEmitter();
varfun=function(){
console.log("My User Define Event Method");
}
eventEmitter.on('myclick',fun);
eventEmitter.emit('myclick');
User Define Module:-
Using this we can create a custom module that can be used in another file.
Step 1st:-
Create Module:-
exports.mymodule = function () {
return"Welcome in user define module";
};
exports.fun = function () {
return"module fun2";
};
Use Module
constum = require('./mymodule')
console.log(um.mymodule())
console.log(um.fun())
What is Blocking & Non-Blocking of Code?
NODE JS API supports the Non-Blocking of the code, it is a unique feature of the NODE JS Application
and it improves the performance of the NODE Application
Blocking of code means if one process is not completed then another process will be
on hold but in non-blocking features,
if one process takes more time to execute then another process can be completed.
Example of Blocking of Code:-
varfs = require("fs");
vardata = fs.readFileSync('hello.txt');
console.log(data.toString());
console.log("Program Ended");
Example of Non-Blocking of Code:-
varfs = require("fs");
fs.readFile('hello.txt', function (err, data) {
if (err) returnconsole.error(err);
console.log(data.toString());
});
console.log("Program Ended");
What is Stream?
Stream objects that are used to read data from the source and write data into the destination.
there are four types of streams −
Readable − Stream which is used for read operation.
Writable − Stream which is used for write operation.
Duplex − Stream which can be used for both read and write operation.
Transform − A type of duplex stream where the output is computed based on input.
The stream can be connected with Event Emitter instance and user various events to perform the operation
data − This event is fired when there is data is available to read.
end − This event is fired when there is no more data to read.
error − This event is fired when there is any error in receiving or writing data.
finish − This event is fired when all the data has been flushed to underlying system.
POST Answer of Questions and ASK to Doubt