Node JS

What is Node.js?

Short Answer: Javascript on the server side

Long Answer: Node.js is a platform built on Chrome’s JavaScript runtime. It’s used to build fast, scalable network applications. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, making it perfect for building real-time applications

Asynchronous I/O

  • Does not need to wait for one process to finish before starting the other (Non-Blocking)
  • Optimize throughput and scalability in web applications with many I/O operations
  • Event-Driven programming
  • This makes Node.js apps extremely fast and efficient

Event Loop

  • Single-threaded
  • Supports concurrency via events and callbacks
  • EventEmitter class is used to bind events and event listeners

img

Simple Example

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {
  if (err){
    console.log(err.stack);
    return;
  }
  console.log(data.toString());
});
console.log("Program Ended");

Using Node

node -v: check node.js version node: Interact with Node Console node filename: Run a file with node

NPM

What is NPM?

  • NPM stands for Node Package Manager
  • The term package is used for back-end and is equivalent to library on the front-end
  • Online repositories for node.js packages/modules
  • Over 200,000 packages available

Using NPM

npm -v: check npm version npm init: create a package.json file (manifest file)

To install a package:

// Add -g: to install globally
// --save: to save info in package.json file
npm install express --save

Installed package can be found in node_modules folder

Then, include the package in a Javascript file

var express = require("express");

Types of Modules

  • Framworks - Express.js
  • Template Engines - Pug, EJS, Handlebars
  • Utilities - Path, OS, API modules, Compilers
  • Database ORM - Mongoose, Mongo.js