What is Node.js?
Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.
(The definition of Node.js as supplied by its official documentation)
What is the difference between AngularJS and Node.js?
Angular.JS is a web application development framework while Node.js is a runtime system.
Why Node.js is being used?
Node.js uses asynchronous programming!
Node.js eliminates the waiting, and simply continues with the next request.
Node.js runs single-threaded, non-blocking, asynchronously programming, which is very memory efficient.
Tooling: Npm is the Node.js package manager and it is excellent. It does, of course, is parallel package managers from other ecosystems, but npm is faster, booming, and logical. It does a great job at defining and fix the project dependencies. It keeps packages alone from other projects, avoiding version strife.
Streaming Data: This software is good in getting high range of data without any discrepancies.
A common task for a web server can be to open a file on the server and return the content to the client.
Here is how PHP or ASP handles a file request:
- Sends the task to the computer’s file system.
- Waits while the file system opens and reads the file.
- Returns the content to the client.
- Ready to handle the next request.
Here is how Node.js handles a file request:
- Sends the task to the computer’s file system.
- Ready to handle the next request.
When the file system has opened and read the file, the server returns the content to the client.
What are the features of Node.js?
Some important features of Node.js:
I/O is Asynchronous and Event Driven: All APIs of Node.js library is asynchronous i.e. non-blocking. So, 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. It is also a reason that it is very fast.
Single threaded: It is follows a single threaded model with event looping.
Highly Scalable: It is highly scalable because event mechanism helps the server to respond in a non-blocking way.
No buffering: Its cuts down the overall processing time while uploading audio and video files. Node.js applications never buffer any data. These applications simply output the data in chunks.
Extremely fast: It is built on Google Chrome’s V8 JavaScript Engine, so its library is very fast in code execution.
Open source: Node.js has an open source community which has produced many excellent modules to add additional capabilities to Node.js applications.
License: It is released under the MIT license.
Why Node uses Google V8 Engine?
Google V8 is Chrome runtime engine which converts JavaScript code into native machine code which in turn provides a fast running application. Microsoft Chakra is another JavaScript engine which can be used with Node.js. It’s not officially declared yet.
What is NPM in Node.Js?
NPM (Node Package Manager) provides following two main functionalities.
NPM works as an online repository for node.js packages/modules which are present at <nodejs.org>.
NPM works as Command line utility to install packages, do version management and dependency management of Node.js packages.
NPM comes bundled along with Node.js installable. We can verify its version using the following command-
$ npm –version
NPM helps to install any Node.js module using the following command.
$ npm install <Module Name>
Node.js web framework module called express– $ npm install express
What are the two types of API functions in Node.js?
There are two types of API functions in Node.js are:
- Non-blocking functions: Asynchronous
- Blocking functions: Synchronous
How does it Work?
The main idea of Node.js: use non-blocking, event-driven I/O to remain lightweight and efficient in the face of data-intensive real-time applications that run across distributed devices.
What is a Node.js File?
Node.js files contain tasks that will be executed on certain events
A typical event is someone trying to access a port on the server
Node.js files must be initiated on the server before having any effect
Node.js files have extension “.js”
How to scale Node application?
We can scale Node application in following ways:
Cloning using cluster module.
Decomposing the application into smaller services – i.e micro services.
What is stream and types of streams?
Streams are a collection of data that might not be available all at once and don’t have to fit in memory. Streams provide chunks of data in a continuous manner. It is useful to read a large set of data and process it.
There are four types of Streams:
Readable: Readable streams as the name suggest used in reading a large chunk of data from a source.
Writeable: Writable streams are used in writing a large chunk of data to the destination.
Transform: Transform stream is the duplex stream which is used in modifying the data (Ex: zip creation).
Duplex: Duplex streams are both readable and writable (Ex: socket).
What is event loop?
Node.js is single threaded but it supports concurrency using events and callbacks. The event loop is a component which checks event queue on a periodic basis and pushes the result in execution stack if the stack is empty.
What is callback hell?
The asynchronous function requires callbacks as a return parameter. When multiple asynchronous functions are chained together then callback hell situation comes up.
What are Error First Callbacks in Node.js?
The error-first callback is s standard protocol for Node.js Callbacks which has a simple rule that the first argument for the callback function should be an error object. If the error argument is not null, then the operations was not successful, error has occurred and if the error argument is null then operation is successful.
What is libuv?
It is a multi-platform support library with a focus on asynchronous I/O. It was primarily developed for use by Node.js, but it’s also used by Luvit, Julia, pyuv, and others.
What is Chaining Process in Node.Js?
It’s an approach to connect the output of one stream to the input of another stream, thus creating a chain of multiple stream operations.
What are the two arguments that async.queue takes?
The two arguments that async.queue takes a) Task function b) Concurrency value
What is <Package.Json>?
It is a plain JSON (JavaScript Object Notation) text file which contains all metadata information about Node.js Project or application. This file should be present in the root directory of every Node.js Package or Module to describe its metadata in JSON format. The file is named as “package” because Node.js platform treats every feature as a separate component. Node.js calls these as Package or Module
Explain the role of REPL in Node.js?
REPL (Read Evaluate 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.
What is Event-driven programming?
Event driven programming is a programming paradigm in which the flow of the program is determined by events like messages from other programs or threads.
Which is the most compatible framework used in NodeJs?
What are Globals in Node.js?
Three keywords in Node.js constitute as Globals. These are:
Global: It represents the Global namespace object and acts as a container for all other objects.
Process: It is one of the global objects but can turn a synchronous function into an async Callback: It can be accessed from anywhere in the code and it primarily gives back information about the application or the environment.
Buffer: It is a class in Node.js to handle binary data.
What is the difference between Node.js vs Ajax vs JQuery?
Node.js: Node.js is a server-side platform for developing client-server applications. For example, if we’ve to build an online employee management system, then we won’t do it using client-side JS. But the Node.js can certainly do it as it runs on a server similar to Apache, Django not in a browser.
AJAX: Aka Asynchronous JavaScript XML (AJAX) is a client-side scripting technique, primarily designed for rendering the contents of a page without refreshing it. There are a no. of large companies utilizing AJAX such as Facebook and Stack Overflow to display dynamic content.
JQuery: JQuery is a famous JavaScript module which complements AJAX, DOM traversal, looping and so on. This library provides many useful functions to help in JavaScript development. However, it’s not mandatory to use it but as it also manages cross-browser compatibility, so can help you produce highly maintainable web applications.
How to solve process out of memory in Node.js?
This error occurs when the memory allocated for the execution application is less than the required memory when run application. By default the memory limit in Node.js is 512 mb, to solve this issue you need to increase the memory limit use command —- max-old-space-size .It can be avoid the memory limit issue.
The following command will start the server.js with a memory limit of 8 GB.
node –max-old-space-size=8192 server.js
Please notice the order of arguments after the node command. You need to add desired parameters first to adjust the related values appropriately. Then, start the file that should run as a Node.js process.
How will you debug an application in Node.js?
Node.js includes a debugging utility called debugger. To enable it start the Node.js with the debug argument followed by the path to the script to debug.
Inserting the statement debugger; into the source code of a script will enable a breakpoint at that position in the code
What are the disadvantages of Node.JS?
Single Threaded: Here one need not care about the synchronization between threads which means that in cases of any problems, the programmers themselves has to solve those problems.
Lack of Maturity: Most of the core libraries have reached the status of stable, and you can trust them to usually do the right thing. But the ecosystem itself is still fairly immature. It’s also not that easy to assess the trait of a particular module (core or otherwise) because of the lack of features for ensuring the quality of code from JavaScript itself.
Hard to make things fault oriented: In JAVA script there are no mechanisms to resolve the errors. For any software particular mechanisms are not found to solve all the problems to make no errors in the coming future.
What are the NodeJS Frameworks?
- Expres.JS
- Meteor JS
- Next.JS
- Hapi.JS
- Koa.JS
- Derby.JS
- Total.JS
- Nest.js
- Loopback.JS
- Sails
- GraphQL Framework
How to create HTTP Server in Nodejs?
To create HTTP Server, use the <http-server> command to do so.
Following is the sample code.
var http = require('http');
var requestListener = function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Welcome Viewers\n');
}
var server = http.createServer(requestListener);
server.listen(8080); // The port where you want to start with.
How to load HTML in Node.js?
To change the “Content-type” in the HTML code from text/plain to text/html.
For Example where we have created a static file in web server.
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(400, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(100);
response.write(file, "binary");
response.end();
});
Now we will modify this code to load an HTML page instead of plain text.
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(400, {"Content-Type": "text/html"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(100, {"Content-Type": "text/html"});
response.write(file);
response.end();
});
What is Got in NodeJS?
Got is a intuitive and powerful HTTP request library for Node.js. It was initially created as a light-weight alternative to the popular Request (now deprecated) package.
What is REPL?
REPL stands for Read Eval Print Loop. It represents a computer environment like a window console or UNIX/Linux shell where a command is entered and system responds with an output.
Read : It reads the input from the user, parses it into JavaScript data structure and then stores it in the memory.
Eval : It executes the data structure.
Print : It prints the result obtained after evaluating the command.
Loop : It loops the above command until the user presses CTRL+C two times.
What are the some REPL commands?
Some REPL commands.
.help : It displays help for all the commands.
tab Keys : It displays the list of all the available commands.
Up/Down Keys : Its is used to determine what command was executed in REPL previously.
.save filename : Save the current REPL session to a file.
.load filename : To Load the specified file in the current REPL session.
ctrl + c : It is used to Terminate the current command.
ctrl + c (twice) : To Exit from the REPL.
ctrl + d : This command performs Exit from the REPL.
.break : It leads Exiting from multiline expression.
.clear : Exit from multiline expression.
Can you explain, which is the first argument usually passed to a Node.js callback handler?
Node.js core modules follow a standard signature for its callback handlers and usually the first argument is an optional error object. And if there is no error, then the argument defaults to null or undefined.
Example:
function callback(error, results) {
// Check for errors before handling results.
if ( error ) {
// Handle error and return.
}
// No error, continue with callback handling.
}
How to make Post request in Node.js?
Following code snippet can be used to make a Post Request in Node.js.
var request = require('request');
request.post(
'https://wwwinterviewgig.com/action',
{ form: { key: 'value' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
How to get Post Data in Node.js?
Following is the code snippet to fetch Post Data using Node.js.
app.use(express.bodyParser());
app.post('/', function(request, response){
console.log(request.body.user);
});
What is Punycode?
Punycode can be defined as an encoding syntax in Node.js which is helpful for converting the Unicode string of characters into ASCII.
punycode = require(‘punycode’);
What is Readfile?
The readFile process is fully buffered which returns response(s) only if the complete file is entered into the buffer and can be read. This process is highly memory intensive and can become slow in case the file size is large.
Can you explain the timing features of Node.js?
A timer module containing multiple functions for the execution of the code after a specific time period is provided by Node.js. Some of the functions provided in this module are:
process.nextTick: This function schedules a callback function which is required to be invoked in the next iteration of the event loop
setTimeout/clearTimeout: This function schedules code execution after the assigned amount of time (in milliseconds)
setImmediate/clearImmediate: This functions executes code at the conclusion of the existing event loop cycle
setInterval/clearInterval: This function is used to execute a block of code a number of times.
What is crypto in Node.js? How is it used?
The crypto module in Node.js is used for cryptography, i.e. includes a set of wrappers for open SSL’s hash, HMAC, sign, decipher, cipher and verify functions.
Here is an example of using cipher for encryption:
const crypto = require('crypto');
const cipher = crypto.createCipher('usrnm', 'pwdd');
var encryptd = cipher.update('Welcome to hackr', 'utf8', 'hex');
encryptd += cipher.final('hex');
console.log(encryptd);
Let’s use decipher to decrypt the above to see if we get the same text back:
const crypto = require('crypto');
const decipher = crypto.createDecipher('usrnm', 'pwdd');
var encryptd = '<enter the previous output-encrypted code here>';
var decryptd = decipher.update(encryptd, 'hex', 'utf8');
decryptd += decipher.final('utf8');
console.log(decryptd);
What is the use of NODE_ENV?
If the project is in the production stage, Node.js promotes the convention of making use of NODE_ENV variable to flag it. This helps in taking better judgment during the development of the projects. Also, when you set your NODE_ENV to production, your application tends to perform 3 times faster.
Can you explain libuv?
Libuv is a multi-platform support library of Node.js which majorly is used for asynchronous I/O. It was primarily developed for Node.js, with time it is popularly practiced with other systems like as Luvit, pyuv, Julia, etc.
Which module is used for file-based operations?
fs module is used.
var fs = require("fs")
Which module is used for buffer-based operations?
buffer module is used.
var buffer = require("buffer")
Which module is used for web-based operations?
http module is used.
var http = require("http")
fs module provides both synchronous as well as asynchronous methods.
true.
How will you read a file using Node?
Following is the syntax of one of the methods to read from a file:
fs.read(fd, buffer, offset, length, position, callback)
What are the NodeJS libraries?
There are some most used NodeJS libraires:
- Express
- Socket.io
- Morgan
- Faker.js
- Async
- Nodemailer
- sequelize
- Moment
- Cheerio
- Bodyparaser
- DotENV
- Cryptojs
- loadsh