Beginner's Guide to Node.js: Tips, Tools, and Best Practices
Date
May 16, 24
Reading Time
6 minutes
Category
Other
- Let’s Begin with NodeJs
- Origin of NodeJs & its Version
- Working of NodeJs
- Applications of NodeJs
- NodeJs Application in Terminal (REPL Terminal)
- NPM (Node Package Manager)
- NVM (Node Version Manager)
- Basic NodeJs Application setup
- NodeJs RestFull API
- Index.html
- Advantages of NodeJs
- Disadvantages of NodeJs
Table of content
Let’s Begin with NodeJs
NodeJs is a JavaScript runtime environment where JavaScript can run outside the Browser. It is an Open source and cross platform environment. It is built on a chrome v8 engine, the core of Google Chrome. V8 Engine runs standalone or can be embedded into any C++ application. Due to this, NodeJs is very fast in Performance and It uses asynchronous programming
Origin of NodeJs & its Version
- NodeJs was created by Ryan Dahl in 2009 and the initial release was on 27th May 2009.
- NPM (Node Package Manager) was created in 2009. The npm Registry is a public collection of packages of open-source code for Node.js
- ExpressJs (It is a minimal and flexible Node.js web application framework) in 2010
- Socket IO (It enables real time bi-directional communication between web clients and server) in 2010
- Hapi (The Simple secure web framework) in 2011
- Koa ( Next Generation web framework for nodeJs Developers an advance of expressJs ) in 2013
- NodeJs foundation in 2015 (OpenJs Foundation)
- NPM private package introduces in 2015
- Node releases its v4 leaving the v1 , v2 , v3 not to be part of the release (2015)
- Yarnpackage manager in 2016
- NodeJs v6 released in 2016
- NodeJs v8 released in 2017
- Http2 introduces in 2017 this module provides an implementation of the HTTP/2 protocol
- NodeJs 10 And then NodeJs 11 released in same year 2018
- NodeJs v12 , V13 in 2019 , v14 , v15 in 2020 and latest v16 in 2021
Working of NodeJs
NodeJs uses “Single Threaded Event Loops” architecture which means it has only a single thread unlike multiple threads in other languages with the help of an event loop it manages the request and handles multiple concurrent clients. NodeJs is based on the Javascript Event-based model and also along with the Javascript callback mechanism. That helps the request to process in an event manner as it gets the request in the event queue and then it processes to event loop which interacts with Non-Blocking operations i.e I/O pulling and it takes the help of Thread Pool which get the work done by providing threads for Blocking operations such as File System, Computations, Database, etc and well that response is been sends back in callback mechanism as the operations execute.
Let's start the operations for better understanding
- NodeJs received the request and placed it into the Event Queue.
- The Request enters the Event Loop and then executes further.
- The Request is for Non-Blocking operations then it will send back the response after the operation is executed as a callback.
- The Request is for Blocking operations, then it takes help from the Thread pool, those threads execute the operation and send back the response as a callback
Hope this makes sense to understand the architecture of NodeJS
Applications of NodeJs
- Internet of Things
- MicroServices
- Single Page Applications
- Real Time Collaboration Tools
- Real Time Chats
- Streaming Application
- Fintech Application
- Content Management system
- Ecommerce Application
NodeJs Application in Terminal (REPL Terminal)
REPL (Read Eval Print Loop) which is a programming language environment. In this we can only write a single line expression as user input and it returns the result in the console after executing code Read : As the name suggests it read the user input and store in memory and parse it to the Javascript Data Structure Eval : It Evaluates the Data Structure Print : It Prints the result Loop: Till the current command terminates ( ctrl + c ), it loops the above command.
REPL Commands
- ctrl + c − terminate the current command.
- ctrl + c twice − terminate the Node REPL
- ctrl + d − terminate the Node REPL
- Up/Down Keys − see command history and modify previous commands
- tab Keys − list of current commands
- .help − list of all commands.
- .break − exit from multiline expression.
- .clear − exit from multiline expression.
- .save filename − save the current Node REPL session to a file.
- .load filename − load file content in current Node REPL session.
- .exit to exit
NPM (Node Package Manager)
NPM is NodeJs package manager. It was created in 2009 by Isaac Z. Schlueter is an open source project for JavaScript developers to share packaged modules of code. NPM registry is an open source collection of packaged modules code for NodeJs Developers which contains the front-end library, routers library, network library, mobile app library and many other libraries or packages which are needed for Javascript Developers.
- NPM is installed with NodeJs to check command npm -v
- Further package install with npm command npm install
- To install a package library globally use -g flag e.g. npm install -g
- To add the package in dev dependency use --save flag e.g. npm install --save
- To update a package use update keyword e.g. npm update
- To uninstall a package use uninstall keyword e.g. npm uninstall
NVM (Node Version Manager)
- nvm is version manager for NodeJs
- nvm can help to switch between versions of nodes as per requirement.
- To install nvm we have to get it from curl or wget
-
- curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
- wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
- To check NVM is install command : nvm -v
- Commands : nvm install 12.6.3
- For more details refer https://github.com/nvm-sh/nvm/blob/master/README.md
Basic NodeJs Application setup
- Create index.js file and write the code const http = require('http'); const requestListner = (req,res) => { res.writeHead(200); res.end('Hello, World') } const server = http.createServer(requestListner); server.listen(8000)
- Need to save the file and then run by node filename.js
- Once its running then hit the browser with localhost:8000
- You will be able to see the message “Hello, World”
NodeJs RestFull API
- Basic NodeJs GET , POST api with Html and Json response respectively. index.js const http = require('http'), url = require('url'), fs = require('fs');var routes = {}; routes['get-request'] = (req,res) => { fs.readFile(__dirname+'/index.html' , (err , data) => { if (err) throw err; res.writeHead(200 , { 'Content-Type':'text/html' }); res.write(data , 'utf8'); res.end(); }); }; routes['post-request'] = (req,res) => { const data = { "status":"success", "Message":"Welcome to NodeJs" } res.writeHead(200,{'Content-Type':'application/json'}); res.write(JSON.stringify(data)) res.end(); } const requestListner = (req,res) => { var path = url.parse(req.url).pathname; var firstPart = path.split('/')[1]; if (routes.hasOwnProperty(firstPart) && req.method == 'GET'){ routesfirstPart; }else if(routes.hasOwnProperty(firstPart) && req.method == 'POST') { routesfirstPart; } else{ res.writeHead(404); res.end("Page Not Found") } } const server = http.createServer(requestListner); server.listen(8000)
Index.html
<html lang="en"> <head > <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge" > <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> NodeJs Basics </title> </head> <body style="text-align: center;"> <h1> Welcome to NodeJs Basics </h1> </body> </html>
- Require package http , fs , url and store in variables.
- The fs module is used to interact with the file system
- The http module is used to interact with the client and server.
- http.createServer(requestListener) creates a server and it calls the requestListener whenever the user requests localhost:8000 listens on the next line on the port which is provided at server.listen(PORT).
- Save index.js with server side code
- Save index.html with client side code.
- To run the code node index.js
Advantages of NodeJs
- High Performance
- It is scalable for modern applications
- Nodejs is cost-effective because of Javascript for both client and server side coding
- It has huge community support.
- Response Time is quick and Boosts Application performance.
- It is good for cross platform applications.
Disadvantages of NodeJs
- Not Suitable for Heavy-Computing Apps.
- Development time is high
- Unstable API