Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 8, 2021 08:36 am GMT

Node.js from Beginners to Advance

What is NodeJs?

Nodejs is a javascript runtime environment. So, what exactly is the javascript runtime? You may be familiar with the term javascript. Javascript is a programming language that you may use to control your DOM in your browser and helps to play with the page loaded in the browser. It is a browser-based scripting language that allows you to interact with a page after it has been loaded, making it a critical component in developing interactive user interfaces in the browser. However, javascript has other exciting uses as well. Nodejs is a modified version of javascript with added features.

Nodejs

So, in a nutshell, Node.js takes javascript and places it in a new environment. You might say that allows you to run javascript code on the server, but it can theoretically run on any system. As a result, you can use javascript in places other than the browser, as if it were another standard programming language. Hence, node js is an excellent solution for creating server-side web apps. So servers are essentially just computers linked to the internet and running anywhere in the world.

So, we can utilize Node.js to run javascript outside of the browser, which is excellent! Nodejs makes use of v8, Google's javascript engine. V8 takes your javascript code and compiles it to machine code. V8 is written in C++, however, you don't need to write any C++ code to utilize javascript or Node.js. So Node.js takes the v8 codebase written in C++ and adds functionalities like dealing with your local file system, opening files, reading files, and deleting files, all of which are unavailable in the browser. Because you can't access your local filesystem in the browser due to security concerns, so, if you install Node.js afterward, you'll be able to use the expanded v8 version. In a nutshell, Nodejs allows you to run JavaScript on your computer and adds helpful functionality to the JavaScript engine, enabling you to do even more insane and fantastic things.

Creating one simple first demo application.

demo application

const fs = require(fs)fs.writeFileSync(Hello.txt,Hello There)

So now we have a basic understanding of what Nodejs is and how to use it. Run Node.js on a server to write server-side code.

server-side js

This is when this server enters the picture. With the server, a computer and IP associated, run some code on that server that does something with the incoming request and provides a response, an HTML page that the browser can then show.

By the way, it's not always simply HTML; it might also include CSS files or Javascript files that contain javascript code for the browser rather than the server. We now do operations on the server that aren't possible on the browser for performance or security reasons.

  • To fetch and save data, we link to databases.

  • We perform user authentication to make it more secure, which we can only do on a location that the user cannot access.

  • We utilize it for input validation to determine if a user typed in the correct e-mail address, and our business logic is stored on the server. Everything that our user shouldn't view since it takes too long to load in the browser.

We obviously want to provide a fast user experience, so we use Node.js and javascript code, but this time not on the browser, but on the server, where we implement these features that Node.js provides, and this is how we indirectly allow our users to interact with the server through that request-response pattern. So we'll utilize Node.js in this session in the same way: we'll use it to develop server-side code that produces data that our users and clients can work with. And it's worth noting that Node.js isn't just for running code on a server; it's also a javascript runtime, which, as you've seen, doesn't require the use of a browser itself.

Nodejs is also frequently used for additional programmings, such as local utility scripts or build tools. Suppose you want to dabble with react, angular, vue, or anything similar. In that case, you'll be using Node.js indirectly a lot for all the build processes that these languages or frameworks require because Node.js is a fantastic tool for developing utility scripts. Nodejs has a significant advantage, or at least one significant advantage, in that it uses Javascript. This language is widely used in current web development for all frontend and build tools, and if you can use it on the server side, you won't have to learn many different languages.

REPL

You can write your node code in one of two ways. One method is to create executable files, while the other is to use REPL. If you simply type node into your terminal, you are now in the REPL, which you can tell by the fact that the complete path of your computer name is no longer included at the start. You may use node commands like console log, two plus two, or writing and interacting with files from there. The lines are not self-contained, and the downside of using a REPL is you lose the entire code after closing. So that's why we utilize executable files, to save them for later.

How does the web work?

web

Let's imagine you're sitting in front of your computer, and you're now visiting a webpage, causing engagement. Assume you're visiting your browser and type in a URL. What happens behind the scenes is that the browser contacts some domain name servers to look up that domain because this domain isn't really your server's address, it's just an encoded human-readable version of that address. Your server has an IP address assigned to it. As a result, you or your browser sends a request to that server at that IP address.

Finally, we've arrived at the point when Node.js comes into action, and your Node.js code is critical. You build the code that runs on that Internet computer with that specific IP address, and you write the code that starts up that server that can handle the incoming request and do something with it. In this code, you can do things like validating user input, communicating with the database (which may operate on a different database server but which you usually reach out to from your backend), and sending back a response to the client.

This response could be some HTML text or HTML code, which the client would handle, or some other type of data, such as a file, JSON, or XML data. The response here is more than just the content, and remember both the response and request have headers, so this is how the web works in general. The transmission of requests and responses is done via a protocol, where HTTP and HTTPS come into play.

  • HTTP(HyperText Transfer Protocol): A protocol for transferring data that is understood by the browser and the server.

  • HTTPS (HyperText Transfer Protocol Secure): A protocol for securely transferring data that is understood by the browser and the server.

Creating own server:

const http = require("http"); const server = http.createServer((req, res) => {  console.log(req);});server.listen(3000);

We will be creating our own server for this project. So for that, we will be utilizing the createServer method that HTTP provides.

Node JS Program Lifecycle.

Node Lifecycle

We used node app.js to run that file because it was named app.js. This essentially launched the script, in which Node.js went through the entire file, parsed the code, registered the variables and functions, and so on, effectively reading our full code and executing it. But then something strange happened: we never left that program. The reason is a key concept in Node.js called the event loop. It's a loop process managed by Node.js that keeps running as long as there is work to be done or event listeners registered.

We passed a function to construct a server, which is essentially a continuous event listener that we didn't unregister from and that we shouldn't because our server should be active at all times. So this event loop is in charge of our primary node application. Nodejs employs an event-driven method for a variety of tasks, not simply server management. The entire node process runs on a single thread on our PC.

Now, as you might expect, if we build a server with Node.js, it should be able to handle multiple millions of incoming requests. If it had to pause and then do something with each request constantly, that would be inefficient, so it uses the event loop concept, where it keeps running in the end and only executes code when a specific event occurs, so it's always available. While this may appear to be okay, if we have two incoming requests, it must handle two events, and yes, it is extremely fast in handling these requests. It does some multi-threading behind the scenes by exploiting the capabilities of the operating system.

Exiting from the event loop

const http = require("http"); const server = http.createServer((req, res) => {  console.log(req);  process.exit();});server.listen(3000);

process.exit() simply unregister/end/quit the entire process

Code Section

Understanding the Request

const http = require("http"); const server = http.createServer((req, res) => {  console.log(req.url, req.method, req.headers);  // process.exit();});server.listen(3000)

Sending the response

const http = require("http");const server = http.createServer((req, res) => {  console.log(req.url, req.method, req.headers);  // process.exit();  res.setHeader("Content-Type", "text/html");  res.write("<html>");  res.write("<head><title>My First Page</title></head>");  res.write("<body><h1>Hello From Node.js Server!</h1></body>");  res.write("</html>");  res.end();});server.listen(3000);

Routing the request

const http = require("http");const server = http.createServer((req, res) => {  const url = req.url;  if (url === "/") {    res.setHeader("Content-Type", "text/html");    res.write("<html>");    res.write("<head><title>Server</title></head>");    res.write(      '<body><form action="/message" method="POST"><input type="text" value=""></form></body>'    );    res.write("</html>");    return res.end();  } else if (url === "/secondserver") {    res.setHeader("Content-Type", "text/html");    res.write("<html>");    res.write("<head><title>Server Page second</title></head>");    res.write("<body><h2>Welcome to the Internet</h2></body>");    res.write("</html>");    res.end();  }  res.setHeader("Content-Type", "text/html");  res.write("<html>");  res.write("<head><title>Server Page second</title></head>");  res.write("<body><h2>Welcome to the Internet</h2></body>");  res.write("</html>");  res.end();});server.listen(3000);

Redirecting Requests

const http = require("http"); const fs = require("fs"); const server = http.createServer((req, res) => {  const url = req.url;  const method = req.method;  if (url === "/") {    res.setHeader("Content-Type", "text/html");    res.write("<html>");    res.write("<head><title>Server</title></head>");    res.write(      '<body><form action="/message" method="POST"><input type="text" value=""></form></body>'    );    res.write("</html>");    return res.end();  }  if (url === "/message" && method === "POST") {    fs.writeFileSync("testing.txt", "YOLO WORLD");    res.statusCode = 302;    res.setHeader("Location", "/");    return res.end();  }    res.setHeader("Content-Type", "text/html");    res.write("<html>");    res.write("<head><title>Server Page second</title></head>");    res.write("<body><h2>Welcome to the Internet</h2></body>");    res.write("</html>");    res.end();});server.listen(3000);

Parsing the request bodies

const http = require("http"); const fs = require("fs"); const server = http.createServer((req, res) => {  const url = req.url;  const method = req.method;  if (url === "/") {    res.write("<html>");    res.write("<head><title>Server</title></head>");    res.write(      '<body><form action="/message" method="POST"><input type="text" name="message" value=""></form></body>'    );    res.write("</html>");    return res.end();  }  if (url === "/message" && method === "POST") {    const body = [];    req.on("data", (chunk) => {      console.log(chunk);      body.push(chunk);    });    req.on("end", () => {      const parseBody = Buffer.concat(body).toString();      const message = parseBody.split("=")[1];      fs.writeFileSync("testing.txt", message);    });    res.statusCode = 302;    res.setHeader("Location", "/");    return res.end();  }    res.setHeader("Content-Type", "text/html");    res.write("<html>");    res.write("<head><title>Server Page second</title></head>");    res.write("<body><h2>Welcome to the Internet</h2></body>");    res.write("</html>");    res.end();});server.listen(3000);

Streams and Buffers:

streams and buffer

Streams are used in Node to handle and process streaming data such as videos, huge files, and so on. All streams in Node.js are managed via the streams module.

There are four different types of streams in Node:

  • Readable streams: To produce a stream of data that can be read, use readable streams.

  • Writable streams: It is used to produce a data stream that can be written to.

  • Duplex stream: To construct a stream that is both reading and writable at the same time, use duplex streams. A duplex stream can be read and written to (for example, a socket connection between a client and a server).

  • Transform streams: To make a readable and written stream with the ability to modify data while reading and writing to it.

Buffers

Streams are based on the concept of buffering. A buffer is a piece of temporary memory used by a stream to store data until it is used.

Click here for full article

Follow @aviyelHQ or sign-up on Aviyel for early access if you are a project maintainer, contributor, or just an Open Source enthusiast.

Twitter =>https://twitter.com/AviyelHq

Official Site => https://aviyel.com


Original Link: https://dev.to/aviyel/node-js-from-beginners-to-advance-31id

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To