Nodejs is a very powerful JavaScript-based framework/platform built on Google Chrome's JavaScript V8 Engine. It is used to develop I/O intensive web applications like video streaming sites, single-page applications, and other web applications. Node.js is open source, completely free, and used by millions of developers around the world. Node.js application are written in JavaScript.
Below are the key features of nodejs: 1. Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, which means non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call. 2. Very Fast Execution − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution. 3. Single Threaded − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as compared to the other traditional servers.
Node.js makes building scalable network programs easy. Some of its advantages include:
A callback function is called at the completion of a given task. This allows other code to be run in the meantime and prevents any blocking. Being an asynchronous platform, Node.js heavily relies on callback. All APIs of Node are written to support callbacks. For example, a function to read a file may start reading file and return the control to the execution environment immediately so that the next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as a parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process a high number of requests without waiting for any function to return results.
Error-first callbacks are used to pass errors and data as well. You have to pass the error as the first parameter, and it has to be checked to see if something went wrong. Additional arguments are used to pass data.
Callback hell is the result of heavily nested callbacks that make our code not only unreadable but also difficult to maintain. Such situation mainly occurs while playing with heavy calculations of data/fetching complex data. For example:
There are different ways to solve the issue of callback hells:
As the name suggests, REPL (Read Eval print Loop) performs the tasks of – Read, Evaluate, Print and Loop. The REPL in Node.js is used to execute ad-hoc Javascript statements. The REPL shell allows entry to javascript directly into a shell prompt and evaluates the results. For the purpose of testing, debugging, or experimenting, REPL is very critical.
NPM (Node package Manager) provides two functionalities:
Node.js and Ajax (Asynchronous JavaScript and XML) are the advanced implementation of JavaScript. They all serve completely different purposes.
Chaining is a mechanism whereby the output of one stream is connected to another stream creating a chain of multiple stream operations.
A stream is an abstract interface for working with streaming data in Node.js. The stream module provides a base API that makes it easy to build objects that implement the stream interface. There are many stream objects provided by Node.js. For instance, a request to an HTTP server and process.stdout are both stream instances. Streams can be readable, writable, or both. All streams are instances of EventEmitter. The stream module can be accessed using: const stream = require('stream'); Types of Streams# There are four fundamental stream types within Node.js:
Exit codes are specific codes that are used to end a “process” (a global object used to represent a node process). Examples of exit codes include:
Node.js, in its essence, is a single thread process. It does not expose child threads and thread management methods to the developer. Technically, Node.js does spawn child threads for certain tasks such as asynchronous I/O, but these run behind the scenes and do not execute any application JavaScript code, nor block the main event loop.
Since Node.js is by default a single thread application, it will run on a single processor core and will not take full advantage of multiple core resources. However, Node.js provides support for deployment on multiple-core systems, to take greater advantage of the hardware. The Cluster module is one of the core Node.js modules and it allows running multiple Node.js worker processes that will share the same port.
All APIs of Node.js library are aynchronous that is non-blocking. It essentially means a Node.js based server never waits for a API to return data. Server moves to next API after calling it and a notification mechanism of Events of Node.js helps server to get response from the previous API call.
Globally installed packages/dependencies are stored in <user-directory>/npm directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js but can not be imported using require() in Node application directly. To install a Node project globally use -g flag.
By default, npm installs any dependency in the local mode. Here local mode refers to the package installation in node_modules directory lying in the folder where Node application is present. Locally deployed packages are accessible via require(). To install a Node project locally following is the syntax
Node js is a single threaded application but it support concurrency via concept of event and callbacks. As every API of Node js are asynchronous and being a single thread, it uses async function calls to maintain the concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever any task get completed, it fires the corresponding event which signals the event listener function to get executed.
EventEmitter class lies in events module. It is accessibly via following syntax: //import events module var events = require('events'); //create an eventEmitter object var eventEmitter = new events.EventEmitter(); When an EventEmitter instance faces any error, it emits an 'error' event. When new listener is added, 'newListener' event is fired and when a listener is removed, 'removeListener' event is fired. EventEmitter provides multiple properties like on and emit. on property is used to bind a function with the event and emit is used to fire an event.
Buffer class is a global class and can be accessed in application without importing buffer module. A Buffer is a kind of an array of integers and corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.
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. There is no limit on piping operations. Consider the above example, where we've read test.txt using readerStream and write test1.txt using writerStream. Now we'll use the piping to simplify our operation or reading from one file and writing to another file.
Each type of Stream is an EventEmitter instance and throws several events at different instance of times. For example, some of the commonly used events are:
Following is the syntax of the method to open a file in asynchronous mode: fs.open(path, flags[, mode], callback) Here is the description of the parameters used: path - This is string having file name including path. flags - Flag tells the behavior of the file to be opened. All possible values have been mentioned below. mode - This sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable. callback - This is the callback function which gets two arguments (err, fd).Parameters
The setTimeout(cb, ms) global function is used to run callback cb after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days. This function returns an opaque value that represents the timer which can be used to clear the timer.
The setInterval(cb, ms) global function is used to run callback cb repeatedly after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days. This function returns an opaque value that represents the timer which can be used to clear the timer using the function clearInterval(t).
Operation errors are the problems with the deployed server/system, like request timeout or hardware failure but programmer errors are actual bugs.
Ryan Dahl created NodeJS and it was initially released in 2009.
NPM is a package manager for the JavaScript programming language. npm, Inc. is a subsidiary of GitHub, that provides hosting for software development and version control with the usage of Git. npm is the default package manager for the JavaScript runtime environment Node.js
Express, Loopback, Koa, Meteor, Sail.js etc
yarn
dependencies are the list of npm packages that is necessary for a project to run, ut devDependencies are the list of dependencies that are reuired only when development and testing.
Google Chrome V8 engine.
Libuv is a cross-platform support library written in C. It was originally written to support Node.js, but now it is also used in Julia, Luvit, Neovim, etc… It is designed around the asynchronous event-driven model.
It is used to get information on current process. Provides multiple events related to process activities.
Streams are objects that let you read data from a source or write data to a destination in the continuous fashion.
PUT is mostly used for update capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource. PATCH submits a partial modification to a resource. If it is needed to only update one field for the resource, you should use the PATCH method.
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It has been called the de facto standard server framework for Node.js. Advantages of Express.js
As Node.js is single-threaded, So normally it uses the single core of the CPU, doesn't take full advantage of multi-core systems. To use all resources of the multi-core systems you can use Cluster module. Clustering in Node.js allows you to create separate processes(as per the number of core available in the system) that can share the same server port.
Global, Process, and Buffer.
In Node.js, each iteration of an Event Loop is called a tick. To schedule a callback function to be invoked in the next iteration of the Event Loop, we use process.nextTick(). It just takes a callback with no time bound, since it will be executing in the next iteration of the Event Loop.
The difference between setTimeout() and process.nextTick() is that the process.nextTick() function is specific to the Node.js Event Loop, But setTimeout() uses JavaScript runtime to schedule its own queue of events.
process.nextTick() is used to schedule a callback function to be invoked in the next iteration of the Event Loop whereas setImmediate() executes a callback on the next cycle of the event loop and it gives back to the event loop for executing any I/O operations.
Memcached is a general-purpose distributed memory caching system. It is often used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of times an external data source (such as a database or API) must be read. Memcached is free and open-source software, licensed under the Revised BSD licence. Memcached runs on Unix-like operating systems (at least LINUX and OS X) and on Microsoft windows. How to Implement Memcached in Nodejs Application