Node JS Interview Questions

1- What is Node.js?
Node.js is an open-source, cross-platform, JavaScript runtime environment that allows developers to build servers and network applications with JavaScript. This means entire sites can be run on a unified JavaScript stack—both the client-side software, and the server-side software.
Technically, it’s a development platform where you can make angular based application.

  Node.js was developed by Ryan Dahl and other developers working at Joyent. It was first released in 2009 supporting only Linux. In 2011, windows version was released.
  1. Node.js is an open source server environment
  2. Node.js uses asynchronous programming.
  3. Node.js uses JavaScript on the server.
2- What Node.js is not?
  •  Node.js is not a JavaScript library, but it is a platform to execute JavaScript on server side.
  •  Node.js programs are written in JavaScript but there is no DOM manipulation provided by Node.js.
 3- What is Heroku?
Heroku is a cloud platform as a service supporting several programming languages that are used as a web application deployment model. Heroku is a platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud. 
https://appdividend.com/

4- What is io.js?
io.js is a fork of the Node.js project which was created in December 2014. It was created to accelerate the development and predicted releases of code under an "open governance model". Since, Node.js was governed by Joyent Inc.

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.

5- What Can Node.js Do?
  1. Node.js can generate dynamic page content
  2. Node.js can create, open, read, write, delete, and close files on the server
  3. Node.js can collect form data
  4. Node.js can add, delete, modify data in your database
6- What is NPM?
Npm, or node package manager: is a command line utility that interacts with a repository of open source projects, Become the package manager for JavaScript. Using npm we can install libraries, packages, and applications, along with their dependencies. It was released in
2011 to share and update open-source libraries like jQuery, AngularJS, React etc.


7- How Node.js is different from other Server Side Frameworks like ASP.NET, Php, JSP and Ruby etc.?
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 (IIS/Tomcat).

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.
8- Where you can deploy Node application?
Node.js app cannot be deployed on your existing hosts like shared web hosting etc. You can use VPS or dedicated servers to install node and run your application.
The easiest way to deploy your Node.js web application is using Cloud server hosting like Windows Azure, Aws, Google, Heroku etc.
Heroku, is completely free and you only need to pay when you are using more resources.

9- What platforms Node.js supports?
Node.js supports following platforms:
1. Linux
2. Windows
3. Mac OS X
4. SunOS

10- What are the advantages of Node.js?
The advantages of node.js are given below:
  • Open Source – Node.js is open source, so it’s free to use and no need to pay for license. 
  • JavaScript as Programming Language – It uses JavaScript as a programming language for both front-end and backend which increase programmer productivity and code reusability.
  • 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, 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.
  • 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.
  • 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.
11-What are the limitations of Node.js?
There are following limitations of Node.js:
  1. It doesn’t support multi-threaded programming.
13- Explain Blocking and non-blocking operations?
By default, In Node.js all I/O operations like file I/O, database operations, network operations etc. are
non-blocking. When these operations are completed, they are notified to the main thread using callback functions. You can also write blocking code for these operations using blocking version of Node.js functions which have Sync word as suffix.
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.

var fs = require('fs' );
//blocking code


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' );
//un-blocking code with the help of callback function
fs.readFile(' text.txt' , 'utf8' , function (err, data) {//doesn’t wait and will
read file asynchronously
console.log(data);
});
console.log("Done!");


/* Output
* Done!
* Hello Node.js
*/


14- Explain Node.js Event Loop?
OR
Explain Node.js Code Execution Process?
Node.js execution model is based on JavaScript Event loop which is single threaded and based on
JavaScript callback mechanism. The event loop facilitates the Node.js to handle concurrent requests. Let’s understand the Node.js execution model with the help of following diagram.

The steps of code execution are given below:
1. Clients send theirs request to Node.js Server.
2. Node.js Server receives those requests and places them into a processing Queue that is known as “Event
Queue”.
3. Node.js uses JavaScript Event Loop to process each client request. This Event loop is an indefinite loop to
receive requests and process them. Event Loop continuously checks for client’s requests placed in Event
Queue. If requests are available, then it process them one by one.
4. If the client request does not require any blocking IO operations, then it process everything, prepare the
response and send it back to the client.
5. If the client request requires some blocking IO operations like interacting with database, file system,
external services then it uses C++ thread pool to process these operations.

Thread pool process steps are as:
  • Event loop checks for thread availability from internal thread pool. If thread is available, then picks up one thread and assign the client request to that thread.
  • Now, this thread is responsible for handling that request, process it, perform blocking IO operations, prepare the response and send it back to the Event Loop.
  • Finally, the Event Loop sends the response to the respective client
15- What is callback?
A callback is a function which passed as an argument to an asynchronous function, that describes what to do after the asynchronous operation has completed. Callbacks are used frequently in node.js development.
var fs = require('fs');
//callback function to read file data
fs.readFile('text.txt', 'utf8',function (err, data) { //callback function  
console.log(data);
});

16- What is Module?
A module is a collection of JavaScript code which encapsulate related code into single unit of code. Node.js has a simple module loading system. A developer can load a JavaScript library or module into his program by using require method as given below:
var http = require('http');

17- What are Node packages and how to install/uninstall them?
OR
What are local packages and global packages?

Node packages are open source libraries that are added into your node project. These packages are
installed in node_modules folder somewhere in your machine. There are two types of Node packages:

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.
npm install angular

If you want to download latest version of AngularJS, you have to specify the version number of that package as:
npm install angular@1.3.5
You can see the list of all installed node packages within the parent working directory by using following command:
npm ls

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.
npm install angular -g
You can see the list of all installed node packages within the parent working directory by using following command:
npm ls
Update Packages
A node package can be updated by using following command.
npm update angular
You can also update global packages by providing the -g option with commands.
npm update angular -g
Uninstalling Packages
A node package can be uninstalled or removed by using following two commands.
npm uninstall angular
npm rm angular
You can also remove global packages by providing the -g option with commands.
npm uninstall angular -g
npm rm angular -g

19- What is package.json file in node project?
Node module dependencies are defined in package.json of your node project. The simple structure of
package.json file is given below:

{
"name": "express-app",
"version": "1.0.0",
"description": "my app",
"main": "server.js",
"author": "",
"license": "ISC",
"dependencies": {
"bootstrap": "^3.3.7",
"express": "^4.15.4",
"express-handlebars": "^3.0.0"
}
}

18- What is the difference between Package dependencies and development dependencies?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": {
"bootstrap": "^3.3.7",
"express": "^4.15.4",
"express-handlebars": "^3.0.0"
}

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

19- What is the difference between module.exports and exports in Node.js?  
In Module.Export, whatever object or data you assign It will be accessible to other modules as well.
Click here
https://www.sitepoint.com/understanding-module-exports-exports-node-js/

20- How to share a variable between Node.js modules?
In Node.js, there is no global context. Each java script code file(module) has its own context. Hence,
defining a variable at the top level scope in a module will not be available in other modules.
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;

Let’s access module1 into module2.
//module2.js
var module1 = require('./module1.js');
console.log(module1.sayHello());

21- What are global variables in Node.js?
Node.js provides you some global variables which are available by default. These are documented in the Node.js API docs: globals and process. Here is a list of global variables provided by Node.js.

Variable Name
Description
__filename Returns the absolute path of the currently executing file
__dirname Returns the absolute path of the directory containing the currently
executing file
process An object which represents the current running process
process.env An object representing the user environment for the current process
process.stdin, process.stout,
process.stderr
Streams which are corresponded to the standard input, standard output
and standard error output for the current process
Process.argv An array containing the command line arguments
22- What are buffers?
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.

23- How to create buffers?
There are following methods to create buffers in Node.js.
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()
//creating buffer from size=2
var buf = new Buffer(2);
buf[0] = 0;
buf[1] = 1;
console.log(buf); //<Buffer 00 01>
console.log(buf.length); //2

//creating buffer from array
var arr = [1, 2, 3];
var buff = new Buffer(arr);
console.log(buff) //<Buffer 01 02 03>
//creating buffer from string
var buffer = new Buffer('Hello World!');
console.log(buffer); //<Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64 21>
console.log(buffer.length); //12

24- How to decode buffers?
Conversion between Buffers and JavaScript string objects requires an explicit encoding method like ascii, utf8, base64, binary, hex etc.
//creating buffer from string
var buffer = new Buffer('Hello World!');
//by default encoding is utf8Page35
console.log(buffer.toString()); //Hello World!
console.log(buffer.toString('ascii')); //Hello World!
console.log(buffer.toString('binary')); //Hello World!
console.log(buffer.toString('hex')); //48656c6c6f20576f726c6421
console.log(buffer.toString('base64')); //SGVsbG8gV29ybGQh

25-What are Streams?
Typically, Stream is a mechanism for transferring data between two points. Node.js provides you streams to read data from the source or to write data to the destination. In Node.js, Streams can be readable, writable, or both and all streams are instances of EventEmitter class.

var http = require('http');
var server = http.createServer(function (req, res) {
// here, req is a readable stream
// here, res is a writable stream
});

26- What are the different types of Streams?
Node.js supports four types of streams as given below:
  • Readable - Used for read operation.
  • Writable - Used for write operation.
  • Duplex - Used for both read and write operations. Both operations are independent and each have separate internal buffer.
  • Transform - A type of duplex stream where the output is computed based on input. Both operations are linked via some transform.  
27- What are Events and Event Emitters?
Node.js core API are based on asynchronous event-driven architecture. Node.js uses events module for event handling. The events module exposes EventEmitter class to deal with events.
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.
An example which creates an event emitter is given below:
  

1
2
3
4
5
6
7
8
var events = require("events");
var emitter = new events.EventEmitter();
//listening 'docall' event
emitter.on("docall", function () {
console.log("ring ring ring")
});
//emitting 'docall' event
emitter.emit("docall");

28- What events are supported by readable streams?
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.  
29- Give an example of readable stream with non-flowing mode?
The readable event is used to read data in non-flowing mode. An example is given below:

var fs = require("fs");
var stream = fs.createReadStream'./input.txt' );
//non-flowing mode: stream pause is not possible
stream.on('readable' , function(){
// read chunk by chunk
var chunk;
while ((chunk = stream.read()) !== null) {
console.log(chunk);
}
});
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);
});

30-Give an example of readable stream with flowing mode?
The data event is used to read data in flowing mode. An example is given below:
var fs = require("fs");
var stream = fs.createReadStream'./input.txt' );
//flowing mode: stream pause is possible
stream.on('data' , function (chunk) {
console.log(chunk); //reading chunk
//pausing stream
stream.pause();
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);
});

31- Give an example of writable stream?
An example of writable stream is given below:
var fs = require("fs");
var data = 'This data is from writable stream!' ;
// create a writable stream
var ws = fs.createWriteStream'output.txt' );
// write the data to stream with encoding to be utf8
ws.write(data'utf8' );
// mark the end of file:no more data to read
ws.end();
ws.on('finish' , function() {
console.log"write completed.");
});
ws.on('error' , function(err){
console.log(err.stack);
});

32- What is Streams piping?
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' );
rs.pipe(ws); //streams piping
//Handling events: end and error
rs.on'end' , function () {
console.log"copy has been completed.");
ws.end(); //mark end
});
rs.on'error' , function (err) {
console.log(err.stack);
});

33- How to debug the code in Node.js?
The static languages like C# and Java have tools like Visual Studio and Eclipse respectively for debugging.
Node.js is based on JavaScript and in order to debug your JavaScript code we have console.log() and alert() statements. But Node.js supports other options as well for code debugging. It supports following options:
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.

34- How to debug the code using Node.js Built-In debugger?
It is a non GUI tool to debug the Node.js code. It is used by inserting debugger statements into the code
and run your app in debug mode using command: node debug app.js

//app.js
for (var i = 0; i < 10; i++) {
debugger;
console.log(i);
}

console.log("done debugging!");

The main node debug commands are as follows:
continue – cont, c (continue until the next debugger/break point)
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.

35- How to handle errors in Node.js?
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);
}

By default, Node.js supports asynchronous operations. It is difficult to write synchronous operations in Node.js. So, if you will use try/catch with Node.js asynchronous code, at the time of throwing the exception it will not be in the stack. This will generate an uncaught exception. Hence, you should use try/catch block with Node.js to handle errors for synchronous code.

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 (reqres) {
    db.query'sql_query' , function (errresult) {
    if (err) {
    res.writeHead(500);
    res.end();
    console.log(err);
    }
    else {
    res.send(result);
    }
    });
    });

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.nextTickfunction () {
// 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);

36- What are uses of path module in Node.js?
Node.js provides path module to normalize, join, and resolve file system paths. It also used to find relative paths, extract components from paths and determine the existence of paths.
Note - The path module simply manipulates strings and does not interact with the file system to validate the paths.

37- What functions are provided by path module in Node.js?
Node.js path module provides following functions to manipulate path strings:
  1. path.normalize() - Ensure a predictable format when a source is untrusted or unreliable.
  2. path.join() - Build a single path form the path segments.
  3. path.dirname() - Provide the directory name out from a path.
  4. path.basename() - Provide the final path segment.
  5. path.extname() - Use to slice from the last period(.) to the end of the path string.
  6.  path.resolve() - Resolve a list of path instructions into an absolute path.
38- What is File System module in Node.js?
Node.js provides file system module (fs) to perform file I/O and directory I/O operations. The fs module provides both asynchronous or synchronous way to perform file I/O and directory I/O operations.
The synchronous functions have “Sync” word as suffix with their names and return the value directly. In synchronous file I/O operation, Node doesn’t execute any other code while the I/O is being performed.
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.

39- What functions are provided by fs module to perform I/O operations on a file?
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" ;
//open file at given path to read ('r' - read mode)
fs.open(path'r' , function (errfd) {
fs.fstat(fdfunction (errstats) {
var totalBytes = stats.size;
var bytesRead = 0;
var buffer = new Buffer(totalBytes);
//Each call to ensure that chunk size is not too small; not too large
var chunkSize = Math.min(512totalBytes);
while (bytesRead < totalBytes) {
//for reading last chunk
if ((bytesRead + chunkSize) > totalBytes) {
chunkSize = totalBytes - bytesRead;
}
//reading the file byte by byte
fs.read(fdbufferbytesReadchunkSizebytesReaderror);
bytesRead += chunkSize;
}
function error(err) {
if (err) {
console.log"File read aborted!!" );
console.log(err);
fs.close(fdfunction () {
consolelog("File closed!!");
});
}
}
fs.close(fdfunction () {
console.log("File closed!!");
});
console.log("File read completed!!" );
console.log("Total bytes read: " + totalBytes);
//display on screen
console.log(buffer.toString());
});
});

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(pathfunction(errstats) {
console.log(stats);
});
//appended
fs.appendFile('./fs-write.txt' , \nAppended Data' , function(err) {
if (errthrow err;
console.log'Append completed!' );
});
//renamed
fs.rename('./fs-write.txt' , './fs-write.bak' , function (err) {
if (errthrow err;
console.log'Rename completed!' );
});
//moving file
fs.rename('./fs-write.txt' , './content/fs-write.txt' , function (err) {
if (errthrow err;
console.log'Move completed!' );
});
//deleted
fs.unlink('./fs-write.bak' , function (err) {
if (errthrow err;
console.log'Deleted successfully!' );
});
// Change permission to readonly
fs.chmod(' ./fs-write.txt' , ' 444' , function (err) {
if(errthrow err;
console.log"changed permission" );
});

fs.read(fd, buffer, offset, length, position, callback) – Read a file byte by byte.
fs.readFile(path, [options], callback) - Fetch the entire file at once at given path.
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");
//Fetching an entire file at once
fs.readFile("./text.txt""utf8"function(errdata) {
if(err) {
console.write(err);
}
else{
console.log(data);
}
});
//open file and write to it byte by byte
fs.open"fs-write.txt""w"function (errfd) {
var buffer = new Buffer'This is a File System write operation' );
var totalBytes = buffer.length;
var bytesWrite = 0;
//Each call to ensure that chunk size is not too small; not too large
var chunkSize = Math.min(15totalBytes);
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(fdbufferbytesWritechunkSizebytesWriteerror);
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!!" );
console.log"Total bytes written: " + totalBytes);
});//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" );
}
});

40- What functions are provided by fs module to perform I/O operations on a directory?
Node.js fs module provides following functions to perform directory I/O operations:
fs.readdir(path, callback) - Read a directory.
fs.mkdir(path[, mode], callback) - Make a directory.
fs.rmdir(path, [callback]) - Remove a directory.
var fs = require("fs");
//reading directory attributes
var path = 'C: \Downloads' ;
fs.readdir(pathfunction (errfiles) {
if (err) {
console.log(err);
}
else {
files.forEach(function (file) {
var filepath = path + "/" + file;
fs.stat(filepathfunction (errstats) {
console.log(filepath);
console.log(stats);
});
});
}
});
// make a new directory
var path = 'C:/test' ; //new dir_name
fs.mkdir(path0666function (err) {
if (err) {
console.log(err.stack);
else {
console.log('Created test dir' );
}
});var path2 = 'C:/mytest' ; //existing dir_name
//remove directory at given path
fs.rmdir(path2function (err) {
if (err) {
console.log(err.stack);
else {
console.log('Removed test dir' );
}
});


41- How to check a file/directory existence in node.js?
In Node.js 4.x or higher, fs.stat() function is recommended to find out the existence of a file/directory.
Both path.exists() and fs.exists() functions have been deprecated from Node.js v0.12.x
var fsrequire"fs");
fs.stat'./fs-write.txt' , function(errstats) {
if (err) {
if (err.code == 'ENOENT' ) {
console.log('Does not exist.' );
}
else {
if (stats.isFile()) {
console.log('File found.' );
else if (stats.isDirectory()) {
console.log('Directory found.' );
}
}
});

42- Which types of network application you can build using node.js?
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.

43- How to create TCP Server and TCP Client?
Node.js "net" module is used for TCP network communication. "net" module is used to create both server and client. net.createServer() method is used to create a TCP server. net.connect() and net.createConnection() methods are used to create TCP client.

var net = require'net' );
//creating TCP Server
var server = net.createServerfunction (socket) {
console.log'client connected' );
socket.on('data' , function (data) {
console.log('client data:' , data.toString());
});
socket.on('end' , function () {
console.log('client disconnected' );
});
//shutting down the Server
socket.on('close' , function () {
console.log('server closed' );
});
socket.on('error' , function (err) {
console.log('Server error:' , err);
});
socket.write('Hello World! \r\n' );
});
server.listen(8081function () {
console.log'server is listening at 8081' );
});
********************************************

var net = require'net' );
//creating TCP client
var client = net.connect({port: 8081}, function () {
console.log'connected to server!' );
});
client.on('connect' , function () {
// writing your "request"
client.write('Hello from client1' );
});
client.on('data' , function (data) {
console.log(data.toString());
client.end();
});
client.on('end' , function () {
console.log'disconnected from server' );
});

44- What is socket?

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, so that communication can happen.

45- How to create an Http Server using Node.js?
  Node.js is best for developing HTTP based application. http module is used to create an http server.

var http=require("http" );
http.createServerfunction(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);
console.log("Server is running at http://localhost:8081");

46- What are Node.js Http module limitations?
       Node.js http module has following limitations:
  •  No cookies handling or parsing.
  •  No built-in session support.
  •  No built-in routing support.
  •  No static file serving.
47- What is Unit Testing?
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.

48- What are node.js unit testing frameworks?
Node.js supports various testing libraries and frameworks to follow test-driven development process. The most popular node.js testing libraries and frameworks are given below:
  1.  Node.js assert
  2.  Mocha
  3.  Chai.js
  4.  Should.js
  5.  Nodeunit
  6.  Vows.js
  7.  Jasmine etc.
49- What is Test Driven Development (TDD)?
TDD is a software development technique to develop software using unit tests. In this approach, test cases are written before any code. And to make test cases pass, the code is written and then refactor the code to make it maintainable.

50- What is Mocha?
Ans. Mocha is a JavaScript test runner for both client (browser) and server-side (node.js). With Mocha you can use a variety of assertion libraries of your choices. Chai is an assertion library widely used with mocha.

51- What are the most popular Node.js ORM?
The most popular Node.js ORM are as:
  1. Sequelize
  2. Node-ORM2
  3. Bookshelf
  4. Waterline
  5. JugglingDB
  6. Mongoose for mongoDB
52- What are JavaScript task runners?
JavaScript task runners are tools to make build operation simple and clean. They save time and automate build operations. JavaScript task runners also help us to manage web development workflow. Grunt and Gulp are the most popular JavaScript task runners for managing web development workflow.

53: List out the differences between AngularJS and NodeJS?
AngularJS is a web application development framework. It’s a JavaScript and it is different from other web app frameworks written in JavaScript like jQuery. NodeJS is a runtime environment used for building server-side applications while AngularJS is a JavaScript framework mainly useful in building/developing client-side part of applications which run inside a web browser.

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives