Node.js is an open-source, cross-platform Javascript runtime environment and libary for running web applications outside the client's browser. It is used for creating server-side web applications. Node.js is perfect for data-intensive applications as it uses an asynchronous, event-driven model.
Node.js is based on V8 engine, it is a virtual machine that utilizes JavaScript as its scripting language and achives high output via non-blocking I/O and single threaded event loop.
Web applications // distributed systems // Network applications
Ther term I/O used to describe any program, operation or device that transfers data to or from a medium and to or from another medium. Every transfer is an output from one medium and an input into another. Medium can be a physical device or network or files within a system.
Frontend: Frontend refers to the client-side of an application. It is that part of a web application that users can see and interact with. It typically includes everything that attributes to the visual aspects of a web applications. HTML, CSS, Javascript, Angular JS and React JS are some of the essentials of frontend development. Backend: Backend refers to the server-side of an application. It constitutes everything that happens behind the scenes. It generally include a web server that communicates with the databasse to server requests. Java, PHP, Python, and Node JS are some backend development technologies.
NPM stands for NOde Package Manager. NPM is responsible for managing all the packages and modules for Node.js. Node Package Manager provides two main functionalities:
- It provides online repositories for node.js packages/modules which are searchable on search.nodejs.org
- It also provides command line utility to install Node.js packages, does version management and dependency management of Node.js packages.
Modules are like JavaScript libraries that can be used in a Node.js application to include a set of functions. To include a module in a Node.js application, use require() function with the parenthesis containing the name of the module.
*Node.js is really fast *Node.js Package Manager has over 1.3M bundles for at the developers disposal *Perfect for data intensive, real-time web applications as Node.js never waits for an API to return data *Better synchronization of code between server and client due to same code base *Easy for web developers to start using Node.js in their projects as it is a Javascript library
MongoDB is the most popularly used databse used with Node.js, it is a NoSQL, cross-platfrom, document-oriented database that provides, high performance, high availbility, easy scalability.
Pros | Cons |
---|---|
Fast processing and an event-based model | Not suitable for heavy computational tasks |
Uses JavaScript which is known by many developers | Using callback is complex since you end up with many nested callbacks |
NPM has over 1.3M packages that provide functionality to an application | Dealing with relatonal database is not a good option for Node.js |
Best suited for streaming huge amounts of data and I/O intensive operations | Since Node.js is single-threaded, CPU intensive tasks is not its strong suit |
Event-Driven programming approach exceedingly uses events to trigger various functions. An event can be anything, such as the pressing of a key or clicking of a mouse button. A call-back function already registered with the elemetns is excuted, whenever an event is triggered.
Asynchronous callbacks are handled by an event loop in Node.js. It is the foundation of the non-blocking input/output in Node.js, making it one of the most important features of the environment
EventEmitter is a class which holds all the onjects that can emit events. Whenever an object from the EventEmitter class thorws an event, all the attached functions are called upon synchronously.
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {};
const myEmitter = newe EventEmitter();
myEmitter.on('event', ()=> {
console.log('an avent occured!') })
myEmitter.emit('event')
Two types of API functions in Node.js:
- Asynchronous, non-blocking functions
- Synchronous, blocking functions
The package.json file is the heart of a Node.js system. The file holds the metadata about a particular project. package.json is present in the root directory of any Node applicaton or module.
The URL module of Node.js provides various utilities for URL resolution and parsing. It is a built-in module that helps in splitting up the web address into a readable format.
var url = require('url')
var addrss = 'http://localhost:8080/default.html?year=2022&month=july';
var que = url.parse(address, true);
console.log(que.host); // returns 'localhost:8080'
console.log(que.pathname); // returns '/default.html'
console.log(que.search); // returns '?year=2022&month=july'
var queData = que.query; // returns an onject: { year: 2022, month: july }
console.log(queData.month); // returns 'july'
Express is flexible Node.js web application framework which provides a wide set of features to develop both web and mobile applications.
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Here in the app.get() section, The request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. And the response object represents the HTTP response that an Express app sends when it gets an HTTP request.
Streams are objects that let you read data from a source or write data to a destination in continuous fashion. In Node.js, there are four types of streams.
- Readable - Stream which is used for read operation.
- Writable - Stream which is used for write operation.
- Duplex - Stream which can be used for both read and write operation.
- Transform - A type of duplex stream where the output is computed based on input.
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
All the API's of Node.js library are asynchronous which means non-blocking. Node.js based server never waits for an API to return data, instead it moves to next API after calling it, and a notification mechanism of Events of Node.js responds to the server for the previous API call.
const doSomethingAsync = () => {
return new Promise(resolve => {
setTimeout(() => resolve('I did something'), 3000)
})
}
const doSomething = async () => {
console.log(await doSomethingAsync())
}
console.log('Before')
doSomething()
console.log('After')
Terminal:
Before
After
I did something
A module in Node.js is used to encapsulate all the related codes into a single uint of code which can be interpreted by shifting all related functions into a single file. You can export a module using module.exports so that it can be imported in another file using require keyword.
A callabck is a function called at the completion of a given task and this prevents any blocking, and allows other code to be run in the meantime.
REPL (also known as Node Shell) stands for Read Eval Print Loop and it represents a computer environment like a window console or unix/linux shell where a command is entered and system responds with an output. Node.js or Node comes bundled with a REPL environment. It performs the following desired tasks.
- Read - Reads user's input, parse the input into JavaScript data-structure and stores in memory.
- Eval - Takes and evaluates the data structure
- Print - Prints the result
- Loop - Loops the above command until user press ctrl-c twice.
Control Flow function is a piece of code which runs in between several asynchronous function calls.
The Control Flow does the following jobs:
- Control the order of execution
- Collect data
- Limit concurrency
- Call the next step in a program
chil_process.fork(modulePath[,args][,options])
- fork() is a particular case of spawn() that generates a new instance of a V8 engine.
- Multiple workers run on a single node code base for multiple tasks.
child_process.spwan(command[,args][,options])
- Spawn() lunches a new process with the available set of commands.
- This method doesn't generate a new V8 instance and only a single copy of the node module is active on the processor.
- Buffer class stores raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap.
- Buffer class is used because pure JavaScript is not compatible with binary data.
- Piping is a mechanism to connect output of one stream to another stream.
- It is normally used to get data from one stream and to pass output of that stream to another stream.
This is the syntax for opening a file in Node.js
fs.open(path, flags[,mode], callback)
- Callback hell, also known as the Pyramid of Doom, is caused by intensively nested, unreadble and unmanageable callbacks, which in turn makes the coder harder to read and debug.
- It is caused by improper implementation on asynchronous logic.
- Reactor Pattern is a concept of non-blocking I/O operations.
- This pattern provides a handler that is associated with each I/O operation and as soon as an I/O request is generated, it is then submitted to a demultiplexer.
- A test pyramid is a figure which explains the proportion of unit tests, integrations tests and end-to-end tests that are required for the proper development of a project.
- The componenets of a test pyramid are given below: Unit Tests: They test the individual units of code in isolation Integrations Tests: They test the integration among dissimilar units End-to-End(E2E): They test the whole system from the User Inteface to the data store and back.
Exit codes are a set of specific codes which are used for finishing a specific process. Given below are some of the exit codes used in Node.js:
- Uncaught fatal exception
- Unused
- Fatal Error
- Internal Exception handler Run-time failure
- Internal JavaScript Evaluation Failure
Middile is a function that receives the Request and Response objects. Most performed tasks by the mmiddleware functions are:
- Execute any type of code
- Update or modify the request and the response objects
- Finish the request-response cycle
- Invoke the next middileware in the stack
NODE_ENV is an environmental variable that stands for node environment in express server. It's how we set and detect which environment we are in.
To set an environment export NODE_ENV=production
Timers module is provided by Node.js which contains various functions for executing the code after a specified period of time. Various functions that are provided by this module: setTimeout/clearTimeout- Used to schedule code execution after a designated amount of milliseconds setInterval/clearInterval- Used to execute a block of code multiple times setImmediate/clearImmediate- Used to execute code at the end of the current event loop cycle