Tuesday , March 5 2024
Home / Node.js / Node = Chrome V8 engine + C++

Node = Chrome V8 engine + C++

Q 1. What is Node.js?

Node is runtime environment on which a javascript code can be executed.
Node is built on google v8 engine.
Ryan the creator of Node, integrated google chrome v8 engine with a C++ program and called it NODE.
Node.js is a single-threaded but highly scalable system that utilizes JavaScript as its scripting language.
Node uses asynchronous, event-driven I/O.
Node is able to achieve high output via single-threaded event loop and non-blocking I/O.
Node.js can be used in developing I/O intensive web applications like
Video streaming sites.
Real-time web applications: A real-time web app is one where information is transmitted (almost) instantaneously between users and the server. This is different from traditional web apps where the client has to ask for information from the server.
EXAMPLE: Chat application
Network applications: Network applications use a client-server architecture, where the client and server are two computers connected to the network. The server is programmed to provide some service to the client.
EXAMPLE: File Transfer between two accounts on two computers (FTP)
Real time video conferencing
General-purpose applications.
Distributed systems. A distributed system is a group of computers working together as to appear as a single computer to the end-user.
Chat applications.
Game servers.
We should not use node for CPU intensive applications like:
Video Encoding.
Image process.
Node.js also provides a rich library of various javascript modules

Q 2. What are the benefits of using Node.js?

  1. Fast
    Node.js is built on Google Chrome’s V8 JavaScript Engine which makes its library very fast in code execution
  2. Asynchronous
    Node.js based server never waits for an API to return data thus making it asynchronous
  3. Scalable
    It is highly scalable because of its event mechanism which helps the server to respond in a non-blocking way
  4. Open Source
    Node.js has an extensive open source community which has contributed in producing some excellent modules to add additional capabilities to Node.js applications
  5. No Buffering
    Node.js applications simply output the data in chunks and never buffer any data.

Q 3. What do you mean by Asynchronous API?
Asynchronous API means they are non-blocking.
Node base server never wait for API to return data. Server moves to next API after calling it. Notification of Events helps server to get response from the previous API call.
All APIs of Node.js are asynchronous. This feature means that if a Node receives a request for some Input/Output operation, it will execute that operation in the background and continue with the processing of other requests. Thus, it will not wait for the response from the previous requests.
Converting Synchronous Code into Asynchronous Code

function getData(param,callback){
var multi = param*2;

Q 4. What is REPL in context of Node?
Node.js comes with virtual environment called REPL (READ+EVAL+PRINT+LOOP)

Q 5. What is the difference of using var and not using var in REPL while dealing with variables?
If var keyword is not used then value is stored in the variable and printed.
If var keyword is used then value is stored but not printed. You can use both variables later.

Q 6. What is the use of Underscore variable in REPL?
Use _ to get the last result.

Q 7. What is npm?
npm stands for Node Package Manager. Provide 2 main facilities.
Online repositories for node.js
Command line utility to install and manage packages.

Q 8. What is global installation of dependencies?
They are stored in /npm directory.

Q 9. What is local installation of dependencies?
They are stored in node_modules directory lying in the folder where Node application is present

Q 10. How to check the already installed dependencies which are globally installed using npm?
npm ls -g

Q 11. What is Package.json?
These files exist in root of application and is used to define the properties of a package.

Q 12. Name some of the attributes of package.json?
name – name of the package
version – version of the package
description – description of the package
Dependencies – npm automatically installs all the dependencies in the node_module folder mentioned here.

Q 13. How to uninstall a dependency using npm?
npm uninstall dependency-name

Q 14. How to update a dependency using npm?
Update package.json and change the version of the dependency which to be updated and run command npm update

Q 15. What is Callback?
Callback is a function called at the completion of a given task.
This prevents any blocking, and allows other code to be run in the meantime.
Callback function take 2 argument First one is “err” and other is “data”.
Example: A function to read a file may start reading file and return the control to execution environment immediately so that 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 parameter. So there is no blocking or wait for File I/O.

function getData(param,callback){
var multi = param+2; callback(multi);

Code Example1:-

var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log("Program Ended");

Code Example2:-

.get("http://www.google.com", function(err, data) {

Q 16. What is callback hell ?
It consists of multiple nested callbacks which makes code hard to read and debug and hence called as callback hell.
Example Code:

async3(function(){ .... });

Example Code:

User.get(request.user, function(err, user) {
if (err) {
} else {
Notebook.get(user.notebook, function(err, notebook) {
if (err) {
return response.send(err);
} else {
doSomethingAsync(user, notebook, function(err, result) {
if (err) {
} else {

Q 17. What is Promises ?
A promise is an object that represents a value which will eventually be available. It might already be available, or it might be ready in a little while.
We interact with promises by passing a callback to its then function

Example Code:

new Promise(function(resolve,reject){
resolve(1) },2000);
}) .then(function(result){
return result*2
}) .then(function(result){
return result*2
}) .catch(function(err){

Example Code in node using popsicle(promise-based HTTP request library):

.then(function(response) {
}) .catch(function(err) {

The main difference in simple callback call and using Promise here is that we are passing our callback to then.

Q 18. How Promises Work ?
A promise is an object which can be returned synchronously from an asynchronous function. It will be in one of 3 possible states:
Fulfilled: onFulfilled() will be called (e.g., resolve() was called)
Rejected: onRejected() will be called (e.g., reject() was called)
Pending: not yet fulfilled or rejected
A promise is settled if it’s not pending (it has been resolved or rejected).

Q 19. What is async/await ?

With Node v8, the async/await feature was officially rolled out by the Node to deal with Promises and function chaining. The functions need not to be chained one after another, simply await the function that returns the Promise. But the function async needs to be declared before awaiting a function returning a Promise.

var example = require(‘example-library’);

(promise library like Q, Popsicle)

var runDemo = async function() {
try {
var firstResponse = await example.firstAsyncRequest();
var secondResponse = await example.secondAsyncRequest(firstResponse);
var thirdAsyncRequest = await example.thirdAsyncRequest(secondResponse);
} catch (error) {
// Handle error

Q 20. What is a blocking code?
Code due to which application has to wait for some I/O operation in order to complete its execution that is known as blocking code.

Q 21. What is Event Loop?
Node js is a single threaded but it support concurrency(parallelism) via concept of event and callbacks.
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.
Single Threaded Event Loop Model Processing Steps:
Clients Send request to Web Server.
Node JS Web Server receives those requests and places them into a Queue. It is known as “Event Queue”.
Node JS Web Server internally has a Component, known as “Event Loop”. Event Loop uses Single Thread only. It is main heart of Node JS Platform Processing Model.
Even Loop checks any Client Request is placed in Event Queue. If no, then wait for incoming requests for indefinitely.
If yes, then pick up one Client Request from Event Queue
Starts process that Client Request
If that Client Request Does Not requires any Blocking IO Operations, then process everything, prepare response and send it back to client.
If that Client Request requires some Blocking IO Operations like interacting with Database, File System, External Services then it will follow different approach
Checks Threads availability from Internal Thread Pool (Child thread)
Picks up one Thread and assign this Client Request to that thread.
That Thread is responsible for taking that request, process it, perform Blocking IO operations, prepare response and send it back to the Event Loop
Event Loop in turn, sends that Response to the respective Client.

Q 22. What is Event Emitter?
EventEmitter class lies in events module.

var events = require('events');
var eventEmitter = new events.EventEmitter();

//EventEmitter provides multiple properties like on and emit.

var myEventHandler = function () {
console.log('I hear a scream!');

//on property is used to bind a function with the event.

eventEmitter.on('scream', myEventHandler);

//emit is used to fire an event.


Q 23. What is purpose of Buffer class in Node?
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.
Creates a Buffer object from an object (string/array/buffer) var buf = Buffer.from(‘abc’); console.log(buf);
Creates a Buffer object of the specified length
var buf = Buffer.alloc(15);

Q 24. What are streams?
Streams are objects that let you read data from a source or write data to a destination in continuous fashion.

Q 25. How many types of streams are present in Node?
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.

Q 26. Name some of the events fired by streams?
data – This event is fired when there is data is available to read.
end – This event is fired when there is no more data to read.
error – This event is fired when there is any error receiving or writing data.
finish – This event is fired when all data has been flushed to underlying system

Q 27. What is Piping in Node?
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.

Q 28. What is Chaining in Node?
Chaining is a mechanism to connect output of one stream to another stream and create a chain of multiple stream operations. It is normally used with piping operations.

Q 29. How can you avoid callback hells?
modularization: break callbacks into independent functions
use a control flow library, like async
use generators with Promises
use async/await

Q 30. What tools can be used to assure consistent style? Why is it important?
Tools that can help:

Q 31. What’s a stub? Name a use case!
Stubs are functions/programs that simulate the behaviors of components/modules. Stubs provide canned answers to function calls made during test cases.

Q 32. When are background/worker processes useful? How can you handle worker tasks?
Worker processes are extremely useful if you’d like to do data processing in the background, like sending out emails or processing images.
There are lots of options for this like RabbitMQ or Kafka.

Q 33. How can you secure your HTTP cookies against XSS attacks?
XSS occurs when the attacker injects executable JavaScript code into the HTML response.
To mitigate these attacks, you have to set flags on the set-cookie HTTP header:

Q 34. API (Web and C++)
So Apis are the mechanism provided by browser or c++ api’s in node js

Http : Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP).
Body-parser : is an npm plugin for Express that we need to use in order to be able to capture data coming via a form.
lodash : Lodash is an utility library for Node.js that provides helper functions to work with Array, Object, Function, Collection and so on
Lodash is an utility library for Node.js that provides helper functions to work with Array, Object, Function, Collection and so on
Socket.IO is a JavaScript library for realtime web applications. It enables realtime, bi-directional communication between web clients and servers.
Integrating Socket.IO
Socket.IO is composed of two parts:
A server that integrates with the Node.JS HTTP Server: socket.io
A client library that loads on the browser side: socket.io-client

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
io.on('connection', function(socket){
console.log('a user connected');
http.listen(3000, function(){
console.log('listening on *:3000');

Notice that I initialize a new instance of socket.io by passing the http (the HTTP server) object. Then I listen on the connection event for incoming sockets, and I log it to the console.
Now in index.html I add the following snippet before the :

<script src="/socket.io/socket.io.js"></script> <script> var socket = io();


set NODE_ENV=production if(process.env.NODE_ENV === 'production') {
// We are running in production mode
} else {
// We are running in development mode

Every time the event loop takes a full trip, we call it a tick.
When we pass a function to process.nextTick(), we instruct the engine to invoke this function at the end of the current operation, before the next event loop tick starts:

process.nextTick(() => { //do something })

The event loop is busy processing the current function code.
When this operation ends, the JS engine runs all the functions passed to nextTick calls during that operation.
It’s the way we can tell the JS engine to process a function asynchronously (after the current function), but as soon as possible, not queue it.
Calling setTimeout(() => {}, 0) will execute the function at the end of next tick, much later than when using nextTick() which prioritizes the call and executes it just before the beginning of the next tick.
Use nextTick() when you want to make sure that in the next event loop iteration that code is already executed.
To start and create skeleton using express
express –view=ejs
to install dependencies
npm install
start application
npm start (This command is set in package.json file)

router = express.Router();
router.get('',function(req,res){ })
router.post('',function(req,res){ })
res.status(200).send({ "status": "0", "msg": "failed" })

req.param (deprecated)
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.
Middleware functions can perform the following tasks:
Execute any code.
Make changes to the request and the response objects.
End the request-response cycle.
Call the next middleware function in the stack.
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.
An Express application can use the following types of middleware:
Application-level middleware
Router-level middleware
Error-handling middleware
Built-in middleware
Third-party middleware
REST (Representational State Transfer)
It is basically a conversion for creating these http services, so we really use HTTP principal to provide support to
There are 4 HTTP Methods
npm init (this command will create a package.json file)

About v.shakya

I am V.Shakya, Software Developer & Consultant I like to share my ideas, views and knowledge to all of you who come across my website. I am young, enthusiastic, highly motivated and self disciplined person. I completed my studies in Master of Computer Application and currently giving my technical expertise to one of the Big IT company. I have more than fifteen years of experience in vast field of Programming , Designing and Development of websites and various software's.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.