Professional Documents
Culture Documents
All rights reserved. No part of this book can be reproduced or stored in any retrieval system, or transmitted in any
form or by any means, electronic, mechanical, photocopying, recording, uploading on server and scanning without
the prior written permission of the author.
The author of this book has endeavored to ensure the accuracy of the information described in this book.
However, the author cannot guarantee the accuracy related to any interpretation the reader may assume from
reading it.
The author will not be liable for any damages, incidental or consequential caused directly or indirectly by this book
or any of the information provided in it.
Further, readers should be aware that the websites or reference links listed in this book may have changed or
disappeared between when this book was written and when it is read.
All other trademarks referred to in this book are the property of their respective owners.
1
Page
1
Dedication
I dedicate this book to my mother Vriksha Devi and my wife Reshu Chauhan, who inspired me to write
this Book. They deserve to have theirs name on the cover as much as I do for all IT professionals, theirs
support made this possible.
It is my deepest sincerity that I say to all my family members Virendra Singh(father), Jaishree and
Jyoti(sisters), Saksham and Pranay(sons) and to my friends along with all of you who follow my blog
www.dotnet-tricks.com without your continued encouragement and belief in me this book would not
have been feasible.
Shailendra Chauhan
2
Page
2
Introduction
Writing a book has never been an easy task. It takes great effort, consistency with strong determination most
importantly must have wisdom over the subject on which you are going to write.
His inspiration for authoring come from his enthusiasm for technology, analytic and initiative nature. Being a
trainer, architect and blogger and passion for helping people inspire him for writing.
Enormous feedback and support from his previous books which appreciated by all user inspire him to write
Node.js interview questions and answers book.
To get the latest release on Node.js, we encourage you to follow the official Node.js website at www.nodejs.org
Our best wishes always with you for your interview and growth!
3
Page
3
About the Author
Shailendra is the author of some of most popular e-books which encompass technical Interview on AngularJS
Interview Questions and Answers, LINQ Interview Questions and Answers and MVC Interview Questions and
Answers. Furthermore, he is a technical reviewer for book on ASP.NET MVC 4 Mobile App Development.
Shailendra Chauhan is renowned for sharing his working experience, research and knowledge through his reputed
and widely subscribed to blogs - www.dotnet-tricks.com and www.dotnettricks.com. Specifically, his blog
www.dotnet-tricks.com provides a vast storehouse of knowledge and support resources in the field of .NET
technologies worldwide and is listed as a non-Microsoft resource in The Microsoft Official Community Site. His
blogs and training approach provide an easily accessible and highly innovative learning experience for people
everywhere, and from a range of backgrounds and skill levels thereby offering the ultimate in training around the
world.
Moreover, and to his credit he has delivered 200+ training sessions to professionals world-wide in Microsoft .NET
technologies and other technologies including JavaScript, AngularJS, Node.js, Ionic and NoSQL Databases. In
addition, he provides Instructor-led online and classroom training programs for all above technologies.
Shailendra’s strong combination of technical skills and solution development for complex application
architecture with proven leadership and motivational skills have elevated him to a world renowned status,
placing him at the top of the list of most sought after trainers.
“I always keep up with new technologies and learning new skills to deliver the best to my students” says
Shailendra Chauhan, he goes on to acknowledge that the betterment of his followers and enabling his students to
realize their goals are his prime objective and a great source of motivation and satisfaction.
Shailendra Chauhan - “Follow me and you too will have the key that opens the door to success”
4
Page
4
How to Contact Us
Although the author of this book has tried to make this book as accurate as it possible but if there is something
which strikes you as odd, or you find an error in the book please drop a line via e-mail.
shailendra@dotnettricks.com
info@dotnettricks.com
You can also follow us on facebook, twitter, linkedin, google plus or subscribe to RSS feed.
5
Page
5
Our Most Accepted Training Programs by Professionals
Node.js Development Training by Shailendra Chauhan
About the Course Download Course Agenda
The Node.js Development course is primarily designed for UI Developer(s)/Web Developer(s) who want to learn
how to develop high performance, event-driven, real-time and scalable networking and web applications. In this
course, you will learn the Node.js, Express, Bootstrap, Unit Testing and JavaScript Task runner (Grunt, Gulp)
fundamental like JavaScript event loop, express routes, unit test cases, HTTP web server, handle requests &
responses, event-driven communications, handling databases and much more...
Course objectives
At the completion of this course, attendees will be able to;
Describe JavaScript weird parts like prototype, objects, lexical scope, dynamic scope and closure.
Explore Node.js basic and advanced in-depth concepts.
Create and consume REST API.
Create HTTP web server and handling requests & responses.
Handle Sessions, Cookies, and Session Stores.
Perform Node.js database operations with SQL and NoSQL Databases.
Write Unit Test cases using Jasmine/Mocha and Chai.
Use HTML Template engines like Handlebars and Jade.
Install and Publish Node's Package Manager – NPM.
Use JS Task runner like Gulp or Grunt.
Publish their Node.js App on cloud server Heroku.
6
AngularJS Development Training by Shailendra Chauhan
About the Course Download Course Agenda
The AngularJS Development course is primarily designed for UI Developer(s)/Web Developer(s) who want to learn
how to create single page web application using AngularJS. In this course, you will learn the Angular1, Angular2
and TypeScript fundamental like bootstrap process, directives, statements, routes, filters, services, components,
classes, interface, method overloading, arrow function etc. that help you to build rich, scalable, extensible and
high performance single page web application and much more…
Course objectives
At the completion of this course, attendees will be able to;
7
Hybrid Mobile Apps Development Training by Shailendra Chauhan
About the Course Download Course Agenda
The Hybrid Mobile Apps Development course is primarily designed for UI Developer(s)/Web Developer(s) who
want to learn how to create cross platform mobile apps using Ionic, Cordova and AngularJS. In this course, you
will learn how to use AngularJS and Ionic for creating widgets, data listing, spinners etc. and creating mobile apps
using mobile camera, audio, video and database and finally publish it on Google Store, Apple Store.
Course objectives
At the completion of this course, attendees will be able to;
8
ASP.NET MVC with AngularJS Development Training by Shailendra
Chauhan
About the Course Download Course Agenda
The ASP.NET MVC with AngularJS Development course is primarily designed for .NET Beginner(s)/Professional(s)
who want to learn how to create web applications using ASP.NET MVC. In this course, you will learn how to create
web pages, custom validation attributes, custom helpers, querying database using Entity Framework ORM, making
interactive using AngularJS and jQuery, mobile friendly application and finally publish it on IIS.
Course objectives
At the completion of this course, attendees will be able to;
9
ASP.NET Core Development Training by Shailendra Chauhan
About the Course Download Course Agenda
The ASP.NET Core course is primarily designed for .NET Beginner(s)/Professional(s) who want to learn how to
create web applications using cross-platform ASP.NET Core. In this course, you will learn how to create web pages,
custom validation attributes, tag helpers, custom helpers, middleware, querying database using Entity Framework
Core, using JavaScript Task runners - grunt and gulp, mobile friendly application and finally publish it.
Course objectives
At the completion of this course, attendees will be able to;
10
Table of Contents
Node.js Interview Questions and Answers .................................................... 1
Dedication ....................................................................................................... 2
Introduction .................................................................................................... 3
About the Author ............................................................................................ 4
How to Contact Us .......................................................................................... 5
Our Most Accepted Training Programs by Professionals ................................. 6
Node.js Development Training by Shailendra Chauhan .......................................................................................6
About the Course................................................................................................................................................6
Course objectives ...............................................................................................................................................6
AngularJS Development Training by Shailendra Chauhan ...................................................................................7
About the Course................................................................................................................................................7
Course objectives ...............................................................................................................................................7
Hybrid Mobile Apps Development Training by Shailendra Chauhan ..................................................................8
About the Course................................................................................................................................................8
Course objectives ...............................................................................................................................................8
ASP.NET MVC with AngularJS Development Training by Shailendra Chauhan ...................................................9
About the Course................................................................................................................................................9
Course objectives ...............................................................................................................................................9
ASP.NET Core Development Training by Shailendra Chauhan .......................................................................... 10
About the Course............................................................................................................................................. 10
Course objectives ............................................................................................................................................ 10
Node.js .......................................................................................................... 15
Q1. What is Node.js? ...................................................................................................................................... 15
Q2. Who has developed Node.js? .................................................................................................................. 15
Q3. What is io.js? ........................................................................................................................................... 15
Q4. What is Node.js foundation? ................................................................................................................... 16
11
11
Q7. Why to use JavaScript on Server Side? .................................................................................................... 17
Q8. What IDEs you can use for Node.js development? ................................................................................. 17
Q9. How Node.js is different from others Server Side Frameworks like ASP.NET, Php, JSP and Ruby etc.? . 17
Q10. Where you can deploy Node application? .............................................................................................. 18
Q11. Which types of application can be developed using Node.js? ................................................................ 18
Q12. Who are using Node.js for their development? ...................................................................................... 19
Q13. What platforms Node.js supports? ......................................................................................................... 19
Q14. What are the advantages of Node.js? ..................................................................................................... 19
Q15. What are the limitations of Node.js? ...................................................................................................... 20
Q16. Where you can deploy Node.js web application? ................................................................................... 20
Q17. Explain Blocking and non-blocking operations? ...................................................................................... 20
Q18. Explain Node.js Event Loop? ................................................................................................................... 21
Q19. What is callback? ..................................................................................................................................... 22
Q20. What is Callback Hell and how to avoid it? ............................................................................................. 22
Q21. Explain Node.js Architecture? ................................................................................................................. 23
Q22. What is Module? ..................................................................................................................................... 24
Q23. What are core modules in Node.js? ........................................................................................................ 24
Q24. What is REPL Terminal? ........................................................................................................................... 25
Q25. What are the useful commands of REPL Terminal? ................................................................................ 26
Q26. What are the useful shortcuts of REPL Terminal? ................................................................................... 26
Q27. What are Node packages and how to install/uninstall them? ................................................................ 26
Q28. What are the various options to download the version of a node module? .......................................... 28
Q29. What is package.json file in node project?.............................................................................................. 28
Q30. What is the difference between Package dependencies and development dependencies? ................. 30
Q31. What is the difference between module.exports and exports in Node.js? ............................................ 30
Q32. How to share a variable between Node.js modules? .............................................................................. 31
Q33. What are global variables in Node.js? ..................................................................................................... 31
Q34. What are buffers?.................................................................................................................................... 32
Q35. How to create buffers? ............................................................................................................................ 32
Q36. How to decode buffers? .......................................................................................................................... 32
12
14
Node.js
Q1. What is Node.js?
Ans. Node.js is a server side JavaScript environment for developing web applications like as ASP.NET, JSP, Php
etc. It is an open-source and cross-platform framework based on Google's V8 JavaScript Engine.
It is used to build fast and scalable network applications as well as data-intensive real-time web applications. All
versions of Node.js are starting from 0.1.0 releases to 0.1.x, 0.2.x, 0.3.x, 0.4.x, 0.5.x, 0.6.x, 0.7.x, 0.8.x, 0.9.x, 0.10.x,
0.11.x, and 0.12.x. Before merging of Node.js and io.js, it’s last versions was Node.js v0.12.9.
15
All versions of io.js are starting from 1.0 releases to 1.x, 2.x and 3.x. Before merging of Node.js and io.js, it’s last
versions was io.js v3.3.1.
Note: In Sep 14, 2015, Node.js and io.js are merged into a single code base known as Node.js version 4.0. In this
way, the much-awaited Node.js version 1.0 never happened.
In Sep 14, 2015, the Node.js foundation announced the combined release of Node.js and io.js into a single code
base known as Node.js version 4.0. It has a features of Node.js and io.js including a lot of new features of ES6.
It compiles JavaScript to native machine code (IA-32, x86-64, ARM, or MIPS ISAs) before execution.
It is used by many open source projects like Node.js and MongoDB to execute JavaScript on server side.
Page
16
Q7. Why to use JavaScript on Server Side?
Ans. There are following reasons to use JavaScript on Server Side:
Q9. How Node.js is different from others Server Side Frameworks like ASP.NET, Php,
JSP and Ruby etc.?
Ans. Today, Node.js is the most popular and widely used server side framework for small, large and any sized
web app and web application development.
Node.js is different from existing server-side frameworks because it is based on asynchronous events via JavaScript
callback functionality and uses the JavaScript as a programming language. Moreover, everything inside Node.js
runs in single thread.
While existing server-side framework like ASP.NET, JSP and Php etc. are based on multiple threads web server
17
(IIS/Tomcat). In multiple threads system, there is a limit of maximum number of threads, beyond which the
Page
throughput decreases.
17
There are following issues with Multi-threaded systems:
Under heavy load a multi-threaded web server consumes a large amount of memory.
Most of the time threads wait till some I/O operations finish.
Context-switching and scheduling increases drastically with large number of threads.
The easiest way to deploy your node application is to use a scalable service like Heroku, which is completely free
and you only need to pay when you are using more resources.
18
Q12. Who are using Node.js for their development?
Ans. Following companies are using Node.js for their development:
Walmart
E-bay
PayPal
Microsoft
LinkedIn
Yahoo
Google
SAP
IBM
Strong Loop
Dropbox
1. Linux
2. Windows
3. Mac OS X
4. SunOS
Open Source – Node.js is open source, so it’s free to use and no need to pay for license. There are also many open
source modules supported by Node.js.
JavaScript as Programming Language – It uses JavaScript as a programming language for both front-end and back-
end which increase programmer productivity and code reusability.
Scalable – You can scale your Node.js application by using two ways – Horizontal Scaling and Vertical Scaling,
which helps you to improve your application performance.
In Horizontal scaling you can add more nodes to your existing system.
In Vertical scaling you can add more resources to a single node.
Better Performance – It provides better performance, since Node.js I/O operations are non-blocking. Also, it uses
V8 JavaScript engine to execute JavaScript code. V8 engine compiles the JS code directly into machine code which
make it fast.
Caching Support – Node.js supports caching of modules. Hence, when a Node.js modules is requested first time,
19
it is cached into the application memory. So next calls for loading the same module may not cause the module
code to be executed again.
Page
19
Lightweight and Extensible – Node.js is based on JavaScript which can be executed on client side as well as server
side. Also, it supports exchange of data using JSON which is easily consumed by JavaScript. This makes it light
weight as compared to other frameworks.
Node.js is open source. Hence you can extend it as per your need.
REST API Support – Using Node.js you can also develop RESTful services API easily.
Unit Testing – It supports unit testing out of box. You can use any JS unit testing frameworks like Jasmin to test
your Node.js code.
Server Development – Node.js has some built-in API which help you to create different types of Server like HTTP
Server, DNS Server, TCP Server etc.
Community Support – Node.js has a wide community of developers around the world. They are active in
development of new modules or packages to support different types of applications development.
Note
Let’s understand the blocking code and Non-blocking code with the help of example.
Blocking Code: The given code is a blocking code, since it will not continue the execution of the next lines of code
until the read operation is completed.
20
var fs = require('fs');
Page
//blocking code
20
var data = fs.readFileSync('text.txt','utf8'); //wait for reading
console.log(data);
console.log("Done!");
/* Output
* Hello Node.js
* Done!
*/
Un-blocking Code: The above blocking code can be converted into non-blocking code with the help of callback
function. Hence, the given code will continue the execution of the next lines of code without waiting for read
operation to be complete.
var fs = require('fs');
/* Output
* Done!
* Hello Node.js
*/
21
Page
21
The steps of code execution are given below:
var fs = require('fs');
async1(function () {
async2(function () {
async3(function () {
....
22
});
});
Page
});
22
How to Avoid Callback
You can avoid callback hell by avoiding deeply-nested callbacks. You can also use promise object to call your
async function one by one.
// Promise approach
var task1 = async1();
var task2 = task1.then(async2);
var task3 = task2.then(async3);
task3.catch(function () {
// handle thrown errors from task1, task2, task3 here
});
Node.js API – These are written in JavaScript and directly exposed to outer world to interact with Node.js internal
components.
Node.js Binding – These are Core API, which bind the JavaScript with C / C++ libraries.
23
C/C++ Add-ons – You can also develop your Node.js Add-ons using C/C++ to work with Node.js.
Page
23
V8 – It is Google’s open source JavaScript engine, written in C++. Actually, it is a JavaScript VM which compile the
JavaScript code into native machine code instead interpretation. It is the fastest JIT (Just-In-Time) compiler for
JavaScript.
Libuv – It is a multi-platform support C++ library which is responsible for handling thread pool, event loop and
async I/O operations in Node.js. In Node.js, blocking I/O operations are delegated to LibUV modules which has a
fixed size C++ thread pool to handle these operations. When these operations are completed, they are notified to
Event loop.
C-ares – It is a C library for handling async DNS request, name resolves and multiple DNS queries in parallel.
OpenSSL – It is a C library for the implementation of Secure Sockets Layer (SSL v2/v3) and Transport Layer Security
(TLS v1) protocols. It also provides all the necessary cryptography methods like hash, cipher, decipher, sign and
verify etc.
Module Description
Assert It is used by Node.js for testing itself. It can be accessed with require('assert').
Buffer It is used to perform operations on raw bytes of data which reside in memory. It can be
accessed with require('buffer').
Child Process It is used by node.js for managing child processes. It can be accessed with It can be accessed
with require('child_process').
Cluster This module is used by Node.js to take advantage of multi-core systems, so that it can handle
more load. It can be accessed with require('cluster').
Console It is used to write data to console. Node.js has a Console object which contains functions to
write data to console. It can be accessed with require('console').
Crypto It is used to support cryptography for encryption and decryption. It can be accessed with
require('crypto').
Debugger It is used for code debugging. To use this, start Node.js with the debug argument and for
24
24
DNS It is used to perform operations like lookup and resolve on domain names. It can be accessed
with require('dns').
Events It is used for events handling in node.js. In node.js, events are emitted by other node objects.
It can be accessed with require('events').
File System It is used to perform operations on files. It can be accessed with require('fs').
HTTP It is used to create Http server and Http client. It can be accessed with require('http').
Net It used to create TCP server and client which can communicate over a network using TCP
protocol. It can be accessed with require('net').
OS It is used to provide basic operating system related utility functions. It can be accessed with
require('os').
Path It is used to perform operations on paths of files. It can be accessed with
require('path').
Process It is a global object and provides information related to the program execution. You do not
need to load it using require() method.
Query String It is used to deal with query strings.
Stream It is used to stream data between two entities. It can be accessed with
require('stream').
Timers All of the timer functions are global and deals with time. You do not need to load it using
require() method.
Url It is used for URL resolution and parsing. It can be accessed with require('url').
Util It is primarily designed to support the needs of Node.js's internal APIs. It is also useful for
debugging. It can be accessed with require('util').
Vm It provides an access to V8 virtual machine to compile and execute JavaScript code. It can be
accessed with require('vm').
Zlib It is used to compress and decompress data. It can be accessed with require('zlib').
25
Q25. What are the useful commands of REPL Terminal?
Ans. Following is the list of useful commands while working with REPL.
Command Description
.help It shows REPL options and commands.
.break It helps you to exit from multiline expression when you get stuck.
.clear It is an alias for .break.
.exit Exit the REPL
.load It will help you to load JS code form a file into the REPL session.
.save It will save all evaluated command in the REPL session.
Command Description
Ctl + d It will terminate the REPL session.
Up/Down Keys It will iterate through command history.
Tab It will display the list of current available commands.
Local Packages - Local packages are installed at project level. These are installed in node_modules folder of the
parent working directory i.e. project level folder.
For example, you can download the latest version of AngularJS into your project by running following command.
If you want to download latest version of AngularJS, you have to specify the version number of that package as:
You can see the list of all installed node packages within the parent working directory by using following command:
npm ls
26
Page
26
Global Packages - Global packages are installed at global location. Typically, these are installed in
/users/username/AppData/Roaming/npm/node_modules folder in Windows OS.
For example, you can download the latest version of AngularJS by running following command.
You can see the list of all installed node packages within the parent working directory by using following command:
npm ls
Update Packages
You can also update global packages by providing the -g option with commands.
Uninstalling Packages
27
27
npm uninstall angular
npm rm angular
You can also remove global packages by providing the -g option with commands.
Q28. What are the various options to download the version of a node module?
Ans. When you create a Node project, you have to add node modules with version number as dependencies
into your project package.json file. There are following ways to specify the version number for a node module.
Let’s say you want to add a version of AngularJS.
{
"name": "module-name",
"version": "1.0.0",
"description": "An example module",
"author": "shailendra@dotnettricks.com",
"dependencies": {
"angular": "1.3.5"
},
"devDependencies": {
"mocha": "~1.8.1"
28
}
}
Page
28
It can be created by using following node command. After running this command, you have to follow some steps
which are shown in the screen shot.
In this way, your package.json file has been created within your project folder.
29
Page
29
Q30. What is the difference between Package dependencies and development
dependencies?
Ans. Package dependencies and development dependencies, both are defined in package.json file.
Package Dependencies
The dependencies field of package.json file will have all packages listing on which your node project is dependent.
"dependencies": {
"angular": "1.4.8",
"jQuery": "^2.1.4"
}
To do listing of your node module as a dependencies package you need to use either –save flag or –production
flag with node command to install package.
Development Dependencies
The devDependencies field of package.json file will have those packages listing which are only required for testing
and development.
"devDependencies": {
"mocha": " ~1.8.1"
}
To do listing of your node module as a dependencies package you need to use –dev flag with node command to
install package.
Hence, a simplified way to view a JavaScript file in Node could be like this:
//TO DO:
Page
return module.exports;
30
In this way, if you set a property on exports (say exports.foo = 5;) then it will be set to module.exports.foo as well
since in JavaScript objects are passed as references. It means exports and module.exports represent the same
object.
But if you will set exports variable to a value other than module.exports then exports and module.exports will not
represent the same object.
In Node.js to share variables between multiple node modules you have to include the same module in each js file.
//module1.js
var module1 = {
sayHello: function(){
return 'Hello Node.js';
}
};
module.exports = module1;
//module2.js
var module1 = require('./module1.js');
console.log(module1.sayHello());
31
Q34. What are buffers?
Ans. JavaScript language has no mechanism for reading or manipulating streams of binary data. So, Node.js
introduced the Buffer class to deal with binary data. In this way, Buffer is a Node.js special data type to work with
binary data. A buffer length is specified in bytes. By default, buffers are returned in data events by all Stream
classes. Buffers are very fast and light objects as compared to strings. A buffer act like an array of integers, but
cannot be resized.
Method Description
new Buffer(array) Allocates a new buffer using an array.
new Buffer(str[, encoding]) Allocates a new buffer containing the given string. encoding is optional and
defaults to 'utf8'.
new Buffer(size) Allocates a new buffer of size bytes.
new Buffer(buffer) Copies the passed buffer data into a new Buffer instance.
new Buffer(arrayBuffer) Allocates a new buffer using buffer property of a TypedArray or a new
ArrayBuffer().
Example:
In Node, objects that generate events are called event emitters. All objects that emit events are instances of the
EventEmitter class. Event Emitters are based on publish/subscribe pattern. EventEmitter class provides Listeners
for listing events and Emitters for emitting events.
emitter.emit("docall");
33
Q40. What events are supported by readable streams?
Ans. A readable stream supports following five events.
data - This is event is emitted when the data is available to read in flowing mode. In flowing mode, you
can pause and resume streams.
readable - This is event is emitted when the data is available to read in non-flowing mode.
end - This is event is emitted when there is no more data to read.
close - This is event is emitted when the stream and any of its underlying resources (like a file descriptor)
have been closed. This event also indicates that no more events will be emitted.
error - This is event is emitted when there is any error while receiving or writing data.
var fs = require("fs");
var stream = fs.createReadStream('./input.txt');
stream.on('end', function () {
console.log('finished'); //no more data to read
});
stream.on('close', function () {
console.log('closed'); //file has been closed
});
stream.on('error', function (err) {
console.log(err.stack);
});
var fs = require("fs");
var stream = fs.createReadStream('./input.txt');
stream.pause();
34
console.log('wait for 1 second........');
setTimeout(function () {
console.log('data start flowing again.......');
stream.resume();
}, 1000);
});
stream.on('end', function () {
console.log('finished'); //no more data to read
});
stream.on('close', function () {
console.log('closed'); //file has been closed
});
stream.on('error', function (err) {
console.log(err.stack);
});
var fs = require("fs");
var data = 'This data is from writable stream!';
ws.on('finish', function() {
console.log("write completed.");
});
ws.on('error', function(err){
console.log(err.stack);
35
});
Page
35
Q45. What is Streams piping?
Ans. Streams Piping is a way to pass output of one stream as an input to another stream. Node.js provides
pipe() function for this purpose.
The pipe() function attaches a readable stream to a writable stream for passing the data from one stream to
another stream. Let's understand it with an example, here we are reading the data from input.txt and writing it to
another file output.txt.
var fs = require('fs');
var rs = fs.createReadStream('input.txt');
var ws = fs.createWriteStream('output.txt');
1. The Built-In Debugger – A non GUI tool to debug the Node.js code.
2. Node Inspector - A GUI tool to debug the Node.js code with the help of chrome or opera browser.
3. IDE Debuggers – IDE like as WebStorm, Visual Studio Code and eclipse enide etc., support the Node.js code
debugging environment.
//app.js
for (var i = 0; i < 10; i++) {
debugger;
console.log(i);
}
console.log("done debugging!");
36
36
step – next, n (step to the next statement)
step in – step, s (step inside the function call)
step out – out, o (step outside the function call)
Using above listed command you can debug your code easily.
In order to use Node Inspector for debugging, you need to install it globally into your machine using NPM
Once it gets installed, run your Node app by running following command using terminal:
After running above command, you will see the output as given below:
It will open the Chrome (assuming chrome is your default browser) immediately and will show your app code in
debug mode. If it doesn’t not open the browser, simply open your chrome browser and navigate to the address
from the console output (http://127.0.0.1:8080/?port=5858).
Now just enjoy the nice visual debug environment for debugging your Node.js code as given below.
37
Page
37
Q49. How to debug the Node.js code using IDE debuggers?
Ans. IDE like as WebStorm, Visual Studio Code and eclipse enide etc., support the Node.js code debugging
environment. In order to debug your code in WebStorm and Visual Studio code, you have to set up your Node.js
project. After that run it and debug it as given below:
38
Page
38
Q50. How to handle errors in Node.js?
Ans. Error handling is a most important part of building robust Node.js app. If you ignore errors or not dealing
with errors in proper way, your node.js app might crash or be left in an inconsistent state. You can divide the
errors mainly into two categories: developer errors and operational errors.
Developer errors are bugs in the program like typing errors in variables or functions name, passing wrong data,
syntax errors etc.
Operational errors are the issues which typically occur on run time like request timeout, failed to connect to
server, invalid user input or database errors etc.
There are following basic patterns you can use for errors handling in Node.js:
Try/Catch - The most commonly used way to handle errors in any programming language is try/catch blocks.
Also, try/catch block executes in synchronous fashion; hence suitable for compiled languages like C#, Java etc.
try {
throw new Error('throw error');
} catch (e) {
console.log(e);
}
Callback – This way is used to handle errors in any callback without using nested try catch statements. In this
way you have to pass a callback, function(err, result) which will be invoked when the asynchronous operation
completes. Here err parameter returns the error and result is the result of completed operations, depending
on whether the operation succeeded or failed.
//request in express
app.get('/', function (req, res) {
db.query('sql_query', function (err, result) {
if (err) {
res.writeHead(500);
res.end();
console.log(err);
}
else {
res.send(result);
}
});
});
39
Page
39
Event Emitters – In Node.js you can use Event Emitters to emit errors. Event emitters come with native
support for error event. So, instead of throwing the errors emit it when the errors happen and the caller will
listen for error event on the emitter.
This way is useful when your single operation might create multiple errors or multiple results and when a lot
of different asynchronous operations are happening.
var events=require('events');
var emitter = new events.EventEmitter();
function async() {
process.nextTick(function () {
// This emits the "error" event
emitter.emit("error", new Error("Something went wrong"));
});
return emitter;
}
//calling async
var event = async();
event.on("error", function (error) {
// When the "error" event is emitted, this is called
console.error(error);
});
Note - The path module simply manipulates strings and does not interact with the file system to validate the paths.
The synchronous functions have “Sync” word as suffix with their names and return the value directly. In
Page
synchronous file I/O operation, Node doesn’t execute any other code while the I/O is being performed.
40
By default, fs module functions are asynchronous, it means they return the output of the I/O operation as a
parameter to a callback function.
Q54. What functions are provided by fs module to perform I/O operations on a file?
Ans. Node.js fs module provides following functions to perform file I/O operations:
fs.open(path, flags, [mode], callback) - Open a file at given path and callback will receive any exceptions as
first argument and a file descriptor as second argument.
fs.close(fd, callback) - Close a file descriptor. The callback receives one argument as an exception.
var fs = require("fs");
var path = "./fs.txt";
//Each call to ensure that chunk size is not too small; not too large
var chunkSize = Math.min(512, totalBytes);
while (bytesRead < totalBytes) {
//for reading last chunk
if ((bytesRead + chunkSize) > totalBytes) {
chunkSize = totalBytes - bytesRead;
}
//reading the file byte by byte
fs.read(fd, buffer, bytesRead, chunkSize, bytesRead, error);
bytesRead += chunkSize;
}
function error(err) {
if (err) {
console.log("File read aborted!!");
console.log(err);
fs.close(fd, function () {
console.log("File closed!!");
});
}
}
fs.close(fd, function () {
console.log("File closed!!");
});
console.log("File read completed!!");
console.log("Total bytes read: " + totalBytes);
//display on screen
41
console.log(buffer.toString());
});
Page
});
41
fs.rename(oldName, newName, callback) - The callback receives one argument as an exception.
fs.unlink(path, callback) - Delete the file at given path. The callback receives one argument as an exception.
fs.truncate(path, len, callback) – Truncate the file at given path by len bytes. If len is greater, the file length
is padded by appending null bytes (\x00) until len is reached.
fs.chown(path, uid, gid, callback) - Changes the ownership of the file at path . Use this to set whether a user
uid or group gid has access to a file.
fs.chmod(path, mode, callback) - Change the mode (permissions) on a file at path.
fs.stat(path, callback) - Use to read the attributes of a file.
var fs = require("fs");
var path = "./fs.txt";
//read the attributes of a file
fs.stat(path, function(err, stats) {
console.log(stats);
});
//appended
fs.appendFile('./fs-write.txt', '\nAppended Data', function(err) {
if (err) throw err;
console.log('Append completed!');
});
//renamed
fs.rename('./fs-write.txt', './fs-write.bak', function (err) {
if (err) throw err;
console.log('Rename completed!');
});
//moving file
fs.rename('./fs-write.txt', './content/fs-write.txt', function (err) {
if (err) throw err;
console.log('Move completed!');
});
//deleted
fs.unlink('./fs-write.bak', function (err) {
if (err) throw err;
console.log('Deleted successfully!');
});
fs.read(fd, buffer, offset, length, position, callback) – Read a file byte by byte.
Page
fs.readFile(path, [options], callback) - Fetch the entire file at once at given path.
42
fs.write(fd, buffer, offset, length, position, callback) - Write a file byte by byte.
fs.writeFile(path, data, [options], callback) - Write a large chunks of data.
fs.appendFile(path, data, [options], callback) - Similar to fs.writeFile, except that data is appended to the end
of the file.
fs.createWriteStream(path, [options]) - Return a writable stream object for file at path.
fs.createReadStream(path, [options]) - Return a readable stream object for file at path . You can perform
stream operations on the returned object.
var fs = require("fs");
//Each call to ensure that chunk size is not too small; not too large
var chunkSize = Math.min(15, totalBytes);
while (bytesWrite < totalBytes) {
//for writing last chunk
if ((bytesWrite + chunkSize) > totalBytes) {
chunkSize = Math.min(512, (totalBytes - bytesWrite));
}
//writing the file byte by byte
fs.write(fd, buffer, bytesWrite, chunkSize, bytesWrite, error);
bytesWrite += chunkSize;
}
function error(err) {
if (err) {
console.log("File write aborted!!");
console.log(err.stack);
fs.close(fd);
}
}
fs.close(fd);
console.log("File write completed!!");
43
43
//write to file at once
fs.writeFile("fs-write2.txt","fs write operation","utf8", function (err) {
if(err) {
return console.log(err);
}
else {
console.log("File has been written");
}
});
var fs = require("fs");
44
fs.rmdir(path2, function (err) {
if (err) {
console.log(err.stack);
} else {
console.log('Removed test dir');
}
});
Q57. Which types of network application you can build using node.js?
Ans. Node.js is best for developing HTTP based application. But it is not only for developing HTTP based
application. It can be used to develop other types of applications. Like as:
TCP server
Command-line program
Real-time web application
Email server
File server
Proxy server etc.
console.log('client connected');
45
socket.on('data', function (data) {
console.log('client data:', data.toString());
});
socket.on('end', function () {
console.log('client disconnected');
});
server.listen(8081, function () {
console.log('server is listening at 8081');
});
client.on('connect', function () {
// writing your "request"
client.write('Hello from client1');
});
client.on('end', function () {
console.log('disconnected from server');
});
Ans. When two applications communicate over a network, they use sockets. A socket is a combination of an
Internet Protocol (IP) address and a port number. An IP address is used to uniquely identify a device on a network,
Page
46
Q60. What are WebSockets?
Ans. WebSockets are based on the WebSocket protocol which is introduced with Html5. WebSockets allow
two-way communication with a persistent connection over TCP. WebSockets communication looks like HTTP
based communication, but the HTTP part is just to create a handshake between the client and the server. Once
the handshake is successful, both the client and the server can send messages to each other.
WebSockets communication is message-based, which makes it easier than TCP sockets based communication
which is based on streams. WebSockets can be used for communication between browser and server, as well as
Peer-to-Peer (P2P), or direct communication between browsers. WebSocket-Node and Socket.IO are third party
node.js modules for creating a WebSocket server.
var http=require("http");
http.createServer(function(req,res){
res.writeHead(200,{"Content-Type":"text/html"});
res.write("<h1>Hello, Node.js Http Server!</h1>");
res.end(); //to end response
}).listen(8081);
TLS 1.0 also referred to as "SSL 3.1". TLS 1.0 is more secure than SSL v3.0. Current browsers support TLS 1.0 by
default. SSL/TLS are used to secure application-specific protocols such as Http, Ftp, Smtp etc.
Page
47
Q64. How to create an Https Server using Node.js?
Ans. HTTP is a stateless and text-based protocol build on the top of TCP protocol. Https or HTTP Secure is an
encrypted version of HTTP and commonly used when dealing with sensitive data.
For running https server, you need to purchase a SSL certificate from a certificate authority or you have to
generate one yourself.
var fs = require('fs');
var https = require('https');
Now run the server and when you will open it in your browser you will get the following error since it is a self-
signed certificate.
48
Page
48
Just ignore this error and click on option continue to this webpage for checking your https server status. You will
find the message in browser as shown below:
1. First you have to download and configure OpenSSL into your system. Download it from the given url
https://slproweb.com/products/Win32OpenSSL.html. In my windows pc it is installed at C:\OpenSSL-
Win64 location.
2. Now open command prompt and follow the given steps to generate self-signed certificate and key
C:\>cd C:\OpenSSL-Win64\bin
C:\OpenSSL-Win64\bin>openssl.exe
OpenSSL> x509 -req -days 365 -in server.csr -signkey server.key -out
server.crt
49
Q67. How to create a simple chat app using socket.io?
Ans. To create a simple chat app, you need to create a http server using socket.io node module then you need
to create a client using socket.io JavaScript library.
Chat Server
Here is an example to create an http server using Express and Socket.IO. Make sure you have installed express
and socket.io modules using npm.
io.on('connection', function(socket){
socket.on('server_msg', function(msg){
io.emit('client_msg', msg);
});
});
//setting public folder to server static files – html, css, js and images
app.use(express.static(__dirname + '/public'));
//running server
server.listen(3000, function(){
console.log('Server is running on http://localhost:3000');
});
Client
Here is an example to create client to interact with server. Make sure you have downloaded socket.io JavaScript
library from http://socket.io website.
50
<!DOCTYPE html>
Page
<html>
50
<head>
<title>Socket.IO chat</title>
<link href="css/site.css" rel="stylesheet"/>
<script src="js/socket.io-1.4.5.js"></script>
<script src="js/jquery-1.11.1.js"></script>
</head>
<body>
<ul id="messages">
</ul>
<form action="">
<input id="txt_chat" autocomplete="off"/>
<button>Send</button>
</form>
<script type="application/javascript">
//put this code after form tag
var socket = io();
$('form').submit(function () {
var send_msg = $('#txt_chat').val();
socket.emit('server_msg', send_msg);
$('#txt_chat').val('');
return false;
});
socket.on('client_msg', function (msg) {
var receive_msg = $('<li>').text(msg);
$('#messages').append(receive_msg);
});
</script>
</body>
</html>
Now run the node.js server and open the given url http://localhost:3000 in two browser windows. These two
browsers client can communicate to each other as shown below.
51
Page
51
Q68. What is middleware?
Ans. A middleware is a chain of functions which are executed before the request is being processed. It can be
used for various operations like user authentication, logging etc.
You can think connect as a stack of middlewares. You can create a server using connect as given below:
MVC frameworks
Express
Koa
Hapi
52
Sails
Nodal
Page
52
Full-stack frameworks
Meteor
Derby.js
MEAN.IO
MEAN.js
Keystone
Horizon
Restify
LoopBack
ActionHero
Fortune.js
Express is built on the top of http and connect. Express is based on Ruby’s Sinatra framework.
53
Page
53
Q73. Why to use Express?
Ans. You should use Express because provides following features:
All of these methods take the first parameter as representing URL and a sequence of middleware as arguments.
Let’s see the examples to create routes in express.
54
res.send("<h1>This is About Us Page</h1>");
});
//running server
var port = process.env.port || 1306;
app.listen(port);
55
Q79. What are the advantages of template engines?
Ans. There are following advantages of using template engines:
Koa does not use middleware. It provides a set of methods that make writing servers fast and enjoyable.
app.use(function *(){
this; // context
this.request; // koa Request
this.response; // koa Response
this.body = '<h2>Koa Server</h2>';
});
56
Q82. What is Unit Testing?
Ans. Unit testing is a way to test each piece of your code which is called as unit. The idea behind the unit testing
is to ensure the quality of each smaller unit. It verifies the functional behavior of each unit in response to correct
and incorrect cases of input data and verify any assumptions made by the code. Unit test cases are usually written
by the developer who has written that code unit.
Allow you to make big changes into code quickly since you know it's tests are working as expected and
when you make the changes you need to write and run tests again to get it work.
Reduce the number of bugs in production code.
Help you to understand the design of the code since to write tests you need to outline all the conditions
with respect to your code and what outputs you are expecting from the code.
Allow refactoring of code at any time without fear of breaking existing code. In this way it makes the
coding process more agile.
Ensure functional behavior of your code since all the tests have been passed.
Node.js assert
Mocha
Chai.js
Should.js
Nodeunit
Vows.js
Jasmine etc.
it maintainable.
Page
57
Q86. What is Behavior Driven Development (BDD)?
Ans. BDD is an extension/revision of TDD. BDD does focus on the business behaviors rather than
implementation aspect. BDD is an Agile software development technique that encourages collaboration between
developers, QA and non-technical participants in a software development. In simple language, it is like a story
writing.
ATDD is closely related to TDD. In this workflow usually concrete examples are created from a user perspective.
58
Thereafter, acceptance tests are developed and run to see the results of failure with the right code based on these
examples.
Page
58
Q88. What is Jasmine?
Ans. Jasmine is BDD based testing framework that works for both client (browser) and server-side (nodejs)
JavaScript. It also includes easy to understand documentation with code snippets.
Sequelize
Node-ORM2
Bookshelf
Waterline
JugglingDB
Mongoose for mongoDB
59
Grunt and Gulp are the most popular JavaScript task runners for managing web development workflow.
grunt.loadNpmTasks('grunt-contrib-htmlmin');
grunt.initConfig({
htmlmin: { // Task
dist: { // Target
options: { // Target options
removeComments: true,
collapseWhitespace: true
},
files: {
'dist/index.html': 'src/index.html', // 'destination': 'source'
'dist/contact.html': 'src/contact.html'
}
}
}
});
grunt.registerTask('default', ['htmlmin']);
// task
gulp.task('minify-html', function () {
gulp.src('./views/*.html') // path to html files
.pipe(minifyHtml())
60
.pipe(gulp.dest('./dist/views'));
});
Page
60
Q93. What is the difference between Grunt and Gulp?
Ans. The differences between Grunt and Gulp are given below:
Grunt Gulp
Configuration over code Code over Configuration
File based Stream based
5600+ Packages 2300+ Package
Widely used Rising rapidly
Grunt perform the task automation by creating temporary files which are disk I/O operations. In Grunt, to run two
tasks on a group of files you need to configure an input and output for each task which result into two separate
write to the disk as shown in the given fig.
Gulp uses Node streams to group tasks together and process them sequentially in memory. In Gulp, to run two
tasks on a group of files, Gulp requires only one write to the disk as shown in the fig.
61
Page
61
Q95. What is MEAN stack?
Ans. MEAN stands for MongoDB, Express, AngularJS and Node.js. MEAN is a most popular full-stack JavaScript
solution for developing fast, robust and scalable web applications. It uses MongoDB to store data in JSON/BSON
formats which makes it well suited to use with JavaScript. It uses Express as Node.js web application framework.
It uses AngularJS as front-end SPA development. It uses Node.js as Server Side JavaScript environment.
One Language - MEAN stack uses JavaScript as a programming language for both client-side and server-
side. Language unification improve the developer productivity.
One Object - Programmers write code in object oriented fashion and MEAN stack allows you to play
with same object on client-side, server-side and also in database-side. So, there is no need to use
libraries for converting data into objects during client-side and server-side interaction.
NoSQL database – MEAN stack uses most popular NoSQL database (MongoDB) that is extremely flexible
as compared to RDBMS. You don’t need to worry about the schema changes and database migrations.
Cross Platform - All the technologies used by the MEAN stack are cross platform compatible. They can run
on windows, linux, mac etc.
Free and Open Source - All the technologies used by the MEAN stack are free and open-source. Hence,
62
62
Community Support - All the technologies used by the MEAN stack have very good community support.
You will find a lot of samples for Node.js, Express, AngularJS and MongoDB.
And MongoDB stores data in objects. Hence querying MongoDB is easy as compared to RDBMS.
Angular acts as a compiler which compiles html and generate the output. It extends HTML by adding attr, tags &
expressions. Also, it provides so many features as given below:
Events Handling
Powerful Data Binding
63
Routing
63
Form Validations
REST API support using $http, $resource services
Web Storage - Local Storage, Session Storage
Cookies
Animations
Dependency Injection
Testing
Q100. What is the recommended folder structure for MEAN app development?
Ans. A typical folder structure for MEAN application is given below:
Client
Server
64
Page
64
Other Free Interview Books
The author will truly appreciate it, if you will share his additional books among others because he wants it to reach
as many techy people as possible so that they can also get benefited by his contribution.
You can download these books from www.dotnet-tricks.com in PDF format absolutely free.
This book is not only the ASP.NET MVC interview book but it is more
than that. This book helps you to get the depth knowledge of ASP.NET
MVC with a simple and elegant way.
Download
This book is not only help you to learn LINQ but it also be helpful to
learn Entity Framework. This book helps you to do hands on LINQ as
well as preparing yourself for an interview on LINQ.
Download
65
Page
65
AngularJS Interview Questions & Answers
AngularJS Interview Questions and Answers book has been written
with the intent of preparing yourself with solid foundations on
AngularJS – in a short time without wasting your time in googling. As
an author, I have tried to present each topic with the help of
appropriate questions with answers which have suitable examples.
Download
66 Page
66
67
Page
67