DEV Community

Cover image for Node Js
NIKHIL GAUTAM
NIKHIL GAUTAM

Posted on • Updated on

Node Js

WHAT IS NODE JS?
Node.js is an Open source, cross-platform web application JavaScript runtime environment built on Google Chrome’s V8 JavaScript engine.
Node.js comes with a runtime environment on which a JavaScript-based script can be interpreted and executed. This runtime allows running a JavaScript code outside of a browser.

Prequisite: (It may help to learn these first)

  1. HTTP (status codes,headers,etc)
  2. JSON
  3. Arrow Function
  4. Promises
  5. MVC Pattern (Modern view Control )

WHY USE NODE?
Some of the advantages of Node.js include:
a) Node.js library is very fast as it is built on Google Chrome’s V8 JavaScript engine.

b) All APIs in the Node.js library are asynchronous, which means a Node.js based server never waits for an API to return data rather, it moves to the next API after calling it.
c) Node.js uses a single-threaded model with the event looping. The event mechanism helps the server respond in a non-blocking way which makes the server highly scalable.

d) Node.js is portable. It is available in different operating systems like Windows, Linux, macOS, Solaris, freeBSD etc.

Flow diagram of Node.js?

working of node
The above diagram states that

a) The clients send requests to the webserver to interact with the web application. The requests can be blocking or non-blocking.

b) After receiving all the requests, js add those requests to the event queue.

c) After that, the requests are passed through the event loop. It also checks if the requests require any external resources.

d) The event loop processes the non-blocking requests and returns the responses.

e) For a blocking request, a single thread from the thread pool is assigned. This thread is responsible for completing a particular blocking request by accessing external resources like computation, database, file system etc.

f) After completing the task, the response is sent back to the event loop that sends the response back to the client.
NON - BLOCKING I/O
1. Works on a single thread using non-blocking I/O calls.
2.Supports tens of thousands concurrent connections.
3.Optimizes throughput & scalability in apps with many I/O operations.
4.All of this makes Node.js apps very fast & efficient.

What is REPL in the context of Node?

The REPL stands for Read Eval Print Loop.
REPL represents a computer console where a command is given, and the system responds with an output.

Node.js also comes with a REPL environment which is described below,
a) Read: Read and parse the input.
b) Eval: Evaluates the data structure.
c) Print: Prints the result.
d) Loop: Loops the above command until the user terminates.

BEST TYPES OF PROJECTS FOR NODE

  1. REST API & Microservices.
  2. Real Time Services(Chat,Live Updates)
  3. CRUD Apps - Blogs,Shopping Carts, Social Networks.
  4. Tools & Utilities.

NOT GOOD For - Anything that is not CPU intensive.

NPM - NODE PACKAGE MANAGER
1.Install 3rd party packages (framework,libraries,tools,etc)
2.Packages get stored in the "node_mosules" folder.
3.All dependencies are listed in a "package.json" file.
4.NPM scripts can be created to run certain tasks such as run a server.

npm init ----- Generates a package.json file
npm install express ----- Install a package locally
npm install -D nodemon ---- Install as a dev dependency

Make these changes to your package.json file to work with nodemon.

"scripts": {
    "dev": "nodemon server"
  }
Enter fullscreen mode Exit fullscreen mode

npm run dev --- run this command to start your Server.

Package.json: The package.json file is kind of a manifest for your project. It can do a lot of things, completely unrelated. It's a central repository of configuration for tools, for example. It's also where npm and yarn store the names and versions for all the installed packages.

Express : Express is a fast, unopinionated and minimalist web framework for Node.js.

Nodemon : Nodemon is a tool that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected.

Node Modules
-Node Core Modules(path,fs,http,etc)
-3rd party modules/packages installed via NPM
-Custom modules (files)

   const path = require('path'); 
   const myFile = require('./myFile'); 
Enter fullscreen mode Exit fullscreen mode

Module Wrapper Function :NodeJS does not run our code directly, Under the hood it wraps the entire code inside a function before execution. This function is termed as Module Wrapper Function.

(function (exports, require, module, __filename, __dirname) {
  //module code
});
Enter fullscreen mode Exit fullscreen mode

It provides some global-looking variables that are specific to the module, such as:

  • The module and exports object that can be used to export values from the module.
  • The variables like __filename and __dirname, that tells us the module’s absolute filename and its directory path.

Build an HTTP Server
Here is a sample Hello World HTTP web server:

const http = require('http')

const port = process.env.PORT || 3000

const server = http.createServer((req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/html')
  res.end('<h1>Hello, World!</h1>')
})

server.listen(port, () => {
  console.log(`Server running at port ${port}`)
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)