What is Node.Js?
- Node.Js is a JavaScript runtime built on Chrome’s V8 JavaScript engine.
- Node.Js is designed to build scalable network applications.
- Node.Js can be downloaded from the official Node.js website.
- Node.Js is a free and open-source server environment.
- Node.Js allows us to run JavaScript on the server.
- Node.Js can run on multiple operating systems.
Why use Node.Js?
- You can use JavaScript in the entire stack.
- Many famous companies use Node.Js as their backend.
- Node.Js comes with a lot of built-in functional modules.
- Node.Js is fast.
Source code:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Here we define some terminology:
The node.js are contain the following three-part,
1. Import required modules:
2. Create a server:
3. Read the request and return the response:
Here broadly discuss:
Import required module: Firstly create a variable whose name is "require" - a directive to load the HTTP module and return HTTP into http variable.
Code: const http = require("http");
Create a server: in the second step we follow those
1. use created http instance
2. call- http.createServer() method to create a server instance
3. bind it at port -8081::: using listen to the method associated with the server instance.
4. Pass it a function with a request
5. response parameters
Code:
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
Here res means response
Combined step1 and step2 together:
Code:
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Node.Js Modules with Examples
These are the set of functions that we want to include in our application.
we also write also that:
const fs = require("fs");
const text = fs.readFileSync("dele.txt", "utf-8")
console.log("The content of the file is")
console.log(text);
Here,
fs Module: fs.readFileSync:
1. inbuilt application programming interface
2. used to read the file and return its content
3. read files in a synchronous way
fs.readFile() method: a file in a non-blocking asynchronous way
Important note:
1. we are telling node.js to block other parallel processes and do the current file-reading process
2. when the fs.readFileSync() method is called the original node program stops executing
3. node waits for the fs.readFileSync() function to get executed
4. after getting the result of the method the remaining node program is executed.
Syntax: fs.readFileSync( path, options )
const text = fs.readFileSync("dele.txt", "utf-8") Here path = dele.text; options: 'uft-8';
Parameters:
1. relative path of the text file
2. path can be of URL type
Comments
Post a Comment