Thursday, 24 August 2017

Node.js Questions and answers

1.      What is Node.js?

Node.js is a web application framework built on Google Chrome's JavaScript Engine(V8 Engine).
Node.js comes with runtime environment on which a Javascript based script can be interpreted and executed (It is analogus to JVM to JAVA byte code). This runtime allows to execute a JavaScript code on any machine outside a browser. Because of this runtime of Node.js, JavaScript is now can be executed on server as well.
Node.js also provides a rich library of various javascript modules which eases the developement of web application using Node.js to great extents.
Node.js = Runtime Environment + JavaScript Library


2.      What do you mean by Asynchronous API?
All APIs of Node.js library are aynchronous that is non-blocking. It essentially means a Node.js based server never waits for a API to return data. Server moves to next API after calling it and a notification mechanism of Events of Node.js helps server to get response from the previous API call.


3.      What are the benefits of using Node.js?

Following are main benefits of using Node.js
  • Aynchronous and Event DrivenAll APIs of Node.js library are aynchronous that is non-blocking. It essentially means a Node.js based server never waits for a API to return data. Server moves to next API after calling it and a notification mechanism of Events of Node.js helps server to get response from the previous API call.
  • Very Fast Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution.
  • Single Threaded but highly Scalable - Node.js uses a single threaded model with event looping. Event mechanism helps server to respond in a non-bloking ways and makes server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and same program can services much larger number of requests than traditional server like Apache HTTP Server.
  • No Buffering - Node.js applications never buffer any data. These applications simply output the data in chunks.

4.      Is it free to use Node.js?
Yes! Node.js is released under the MIT license and is free to use.

5.      Is Node a single threaded application?
Yes! Node uses a single threaded model with event looping.


6.      What is REPL in context of Node?
REPL stands for Read Eval Print Loop and it represents a computer environment like a window console or unix/linux shell where a command is entered and system responds with an output. Node.js or Node comes bundled with a REPL environment. It performs the following desired tasks.
  • Read - Reads user's input, parse the input into JavaScript data-structure and stores in memory.
  • Eval - Takes and evaluates the data structure
  • Print - Prints the result
  • Loop - Loops the above command until user press ctrl-c twice.


7.      Can we evaluate simple expression using Node REPL
Yes.


8.      What is the difference of using var and not using var in REPL while dealing with variables?
Use variables to store values and print later. if var keyword is not used then value is stored in the variable and printed. Wheras if var keyword is used then value is stored but not printed. You can use both variables later.

9.      What is the use of Underscore variable in REPL?
Use _ to get the last result.
C:\Nodejs_WorkSpace>node
> var x = 10
undefined
> var y = 20
undefined
> x + y
30
> var sum = _
undefined
> console.log(sum)
30
undefined
> 


10.  What is npm?
npm stands for Node Package Manager. npm provides following two main functionalities:
  • Online repositories for node.js packages/modules which are searchable on search.nodejs.org
  • Command line utility to install packages, do version management and dependency management of Node.js packages.


11.  What is global installation of dependencies?
Globally installed packages/dependencies are stored in <user-directory>/npm directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js but can not be imported using require() in Node application directly. To install a Node project globally use -g flag.
C:\Nodejs_WorkSpace>npm install express -g


12.  What is local installation of dependencies?
By default, npm installs any dependency in the local mode. Here local mode refers to the package installation in node_modules directory lying in the folder where Node application is present. Locally deployed packages are accessible via require(). To install a Node project locally following is the syntax.
C:\Nodejs_WorkSpace>npm install express


13.  How to check the already installed dependencies which are globally installed using npm?
Use the following command:
C:\Nodejs_WorkSpace>npm ls -g


14.  What is Package.json?
package.json is present in the root directory of any Node application/module and is used to define the properties of a package.

Name some of the attributes of package.json?
Following are the attributes of Package.json
  • name - name of the package
  • version - version of the package
  • description - description of the package
  • homepage - homepage of the package
  • author - author of the package
  • contributors - name of the contributors to the package
  • dependencies - list of dependencies. npm automatically installs all the dependencies mentioned here in the node_module folder of the package.
  • repository - repository type and url of the package
  • main - entry point of the package
  • keywords - keywords


15.  How to uninstall a dependency using npm?
Use following command to uninstall a module.
C:\Nodejs_WorkSpace>npm uninstall dependency-name

16.  How to update a dependency using npm?
Update package.json and change the version of the dependency which to be updated and run the following command.
C:\Nodejs_WorkSpace>npm update

17.  What is Callback?
Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All APIs of Node are written is such a way that they supports callbacks. For example, a function to read a file may start reading file and return the control to execution environment immidiately so that next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process high number of request without waiting for any function to return result.


18.  What is a blocking code?
If application has to wait for some I/O operation in order to complete its execution any further then the code responsible for waiting is known as blocking code.

19.  How Node prevents blocking code?
By providing callback function. Callback function gets called whenever corresponding event triggered.

20.  What is Event Loop?
Node js is a single threaded application but it support concurrency via concept of event and callbacks. As every API of Node js are asynchronous and being a single thread, it uses async function calls to maintain the concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever any task get completed, it fires the corresponding event which signals the event listener function to get executed.


21.  What is Event Emmitter?

EventEmitter class lies in events module. It is accessibly via following syntax:
//import events module
var events = require('events');
//create an eventEmitter object
var eventEmitter = new events.EventEmitter();
When an EventEmitter instance faces any error, it emits an 'error' event. When new listener is added, 'newListener' event is fired and when a listener is removed, 'removeListener' event is fired.
EventEmitter provides multiple properties like on and emiton property is used to bind a function with the event and emit is used to fire an event.


22.  Which module is used for file based operations?
fs module is used for file based operations.
var fs = require("fs")


23.  Which module is used for file based operations?
fs module is used for file based operations.
var fs = require("fs")

24.  Which module is used for buffer based operations?
buffer module is used for buffer based operations.
var buffer = require("buffer")

25.  Which module is used for web based operations?
http module is used for web based operations
var http = require("http")
fs module provides both synchronous as well as asynchronous methods.

26.  What is difference between synchronous and asynchronous method of fs module?
Every method in fs module have synchronous as well as asynchronous form. Asynchronous methods takes a last parameter as completion function callback and first parameter of the callback function is error. It is preferred to use asynchronous method instead of synchronous method as former never block the program execution where the latter one does.
Name some of the flags used in read/write operation on files.
flags for read/write operations are following:
  • r - Open file for reading. An exception occurs if the file does not exist.
  • r+ - Open file for reading and writing. An exception occurs if the file does not exist.
  • rs - Open file for reading in synchronous mode. Instructs the operating system to bypass the local file system cache. This is primarily useful for opening files on NFS mounts as it allows you to skip the potentially stale local cache. It has a very real impact on I/O performance so don't use this flag unless you need it. Note that this doesn't turn fs.open() into a synchronous blocking call. If that's what you want then you should be using fs.openSync()
  • rs+ - Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs' about using this with caution.
  • w - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
  • wx - Like 'w' but fails if path exists.
  • w+ - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
  • wx+ - Like 'w+' but fails if path exists.
  • a - Open file for appending. The file is created if it does not exist.
  • ax - Like 'a' but fails if path exists.
  • a+ - Open file for reading and appending. The file is created if it does not exist.
  • ax+' - Like 'a+' but fails if path exists.

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

·         How many types of streams are present in Node.

In Node.js, there are four types of streams.
  • Readable - Stream which is used for read operation.
  • Writable - Stream which is used for write operation.
  • Duplex - Stream which can be used for both read and write operation.
  • Transform - A type of duplex stream where the output is computed based on input.

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

29.  How will you open a file using Node?
Following is the syntax of the method to open a file in asynchronous mode:
fs.open(path, flags[, mode], callback)
Parameters
Here is the description of the parameters used:
  • path - This is string having file name including path.
  • flags - Flag tells the behavior of the file to be opened. All possible values have been mentioned below.
  • mode - This sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable.
  • callback - This is the callback function which gets two arguments (err, fd).


30.  How will you read a file using Node?
Following is the syntax of one of the methods to read from a file:
fs.read(fd, buffer, offset, length, position, callback)
This method will use file descriptor to read the file, if you want to read file using file name directly then you should use another method available.
Parameters
Here is the description of the parameters used:
  • fd - This is the file descriptor returned by file fs.open() method.
  • buffer - This is the buffer that the data will be written to.
  • offset - This is the offset in the buffer to start writing at.
  • length - This is an integer specifying the number of bytes to read.
  • position - This is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position.
  • callback - This is the callback function which gets the three arguments, (err, bytesRead, buffer).

31.  How will you write a file using Node?
Following is the syntax of one of the methods to write into a file:
fs.writeFile(filename, data[, options], callback)
This method will over-write the file if file already exists. If you want to write into an existing file then you should use another method available.
Parameters
Here is the description of the parameters used:
  • path - This is string having file name including path.
  • data - This is the String or Buffer to be written into the file.
  • options - The third parameter is an object which will hold {encoding, mode, flag}. By default encoding is utf8, mode is octal value 0666 and flag is 'w'
  • callback - This is the callback function which gets a single parameter err and used to to return error in case of any writing error.

32.  How will you close a file using Node?
Following is the syntax of one of the methods to close an opened file:
fs.close(fd, callback)
Parameters
Here is the description of the parameters used:
  • fd - This is the file descriptor returned by file fs.open() method.
  • callback - This is the callback function which gets no arguments other than a possible exception are given to the completion callback.


How will you get information about a file using Node?
Following is the syntax of the method to get the information about a file:
fs.stat(path, callback)
Parameters
Here is the description of the parameters used:
  • path - This is string having file name including path.
  • callback - This is the callback function which gets two arguments (err, stats) where stats is an object of fs.Stats type which is printed below in the example.
How will you truncate a file using Node?
Following is the syntax of the method to truncate an opened file:
fs.ftruncate(fd, len, callback)
Parameters
Here is the description of the parameters used:
  • fd - This is the file descriptor returned by file fs.open() method.
  • len - This is the length of the file after which file will be truncated.
  • callback - This is the callback function which gets no arguments other than a possible exception are given to the completion callback.
How will you delete a file using Node?
Following is the syntax of the method to delete a file:
fs.unlink(path, callback)
Parameters
Here is the description of the parameters used:
  • path - This is the file name including path.
  • callback - This is the callback function which gets no arguments other than a possible exception are given to the completion callback.
How will you create a directory?
Following is the syntax of the method to create a directory:
fs.mkdir(path[, mode], callback)
Parameters
Here is the description of the parameters used:
  • path - This is the directory name including path.
  • mode - This is the directory permission to be set. Defaults to 0777.
  • callback - This is the callback function which gets no arguments other than a possible exception are given to the completion callback.
How will you delete a directory?
Following is the syntax of the method to remove a directory:
fs.rmdir(path, callback)
Parameters
Here is the description of the parameters used:
  • path - This is the directory name including path.
  • callback - This is the callback function which gets no arguments other than a possible exception are given to the completion callback.
How will you read a directory?
Following is the syntax of the method to read a directory:
fs.readdir(path, callback)
Parameters
Here is the description of the parameters used:
  • path - This is the directory name including path.
  • callback - This is the callback function which gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.
What is the purpose of __filename variable?
The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.
What is the purpose of __dirname variable?
The __dirname represents the name of the directory that the currently executing script resides in.
What is the purpose of setTimeout function?
The setTimeout(cb, ms) global function is used to run callback cb after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days.
This function returns an opaque value that represents the timer which can be used to clear the timer.
What is the purpose of clearTimeout function?
The clearTimeout( t ) global function is used to stop a timer that was previously created with setTimeout(). Here t is the timer returned by setTimeout() function.
What is the purpose of setInterval function?
The setInterval(cb, ms) global function is used to run callback cb repeatedly after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days.
This function returns an opaque value that represents the timer which can be used to clear the timer using the function clearInterval(t).
What is the purpose of console object?
console object is used to Used to print information on stdout and stderr.
What is the purpose of process object?
process object is used to get information on current process. Provides multiple events related to process activities.

1)      What is node.js?
Node.js is a Server side scripting which is used to build scalable programs. Its multiple advantages over other server side languages, the prominent being non-blocking I/O.
2)      How node.js works?
Node.js works on a v8 environment, it is a virtual machine that utilizes JavaScript as its scripting language and achieves high output via non-blocking I/O and single threaded event loop.
3)      What do you mean by the term I/O ?
I/O is the shorthand for input and output, and it will access anything outside of your application. It will be loaded into the machine memory to run the program, once the application is started.

4)      What does event-driven programming mean?
In computer programming, event driven programming is a programming paradigm in which the flow of the program is determined by events like messages from other programs or threads. It is an application architecture technique divided into two sections 1) Event Selection 2) Event Handling
5)      Where can we use node.js?
Node.js can be used for the following purposes
a)      Web applications ( especially real-time web apps )
b)      Network applications
c)       Distributed systems
d)      General purpose applications


6)      What is the advantage of using node.js?
a)      It provides an easy way to build scalable network programs
b)      Generally fast
c)       Great concurrency
d)      Asynchronous everything
e)      Almost never blocks
7)      What are the two types of API functions in Node.js ?
The two types of API functions in Node.js are
a)      Asynchronous, non-blocking functions
b)      Synchronous, blocking functions
8)      What is control flow function?
A generic piece of code which runs in between several asynchronous function calls is known as control flow function.
9)      Explain the steps how “Control Flow” controls the functions calls?
a)      Control the order of execution
b)      Collect data
c)       Limit concurrency
d)      Call the next step in program
10)   Why Node.js is single threaded?
For async processing, Node.js was created explicitly as an experiment. It is believed that more performance and scalability can be achieved by doing async processing on a single thread under typical web loads than the typical thread based implementation.
11)   Does node run on windows?


Yes – it does. Download the MSI installer from http://nodejs.org/download/
12)   Can you access DOM in node?
No, you cannot access DOM in node.
13)   Using the event loop what are the tasks that should be done asynchronously?
a)      I/O operations
b)      Heavy computation
c)       Anything requiring blocking
14)   Why node.js is quickly gaining attention from JAVA programmers?
Node.js is quickly gaining attention as it is a loop based server for JavaScript. Node.js gives user the ability to write the JavaScript on the server, which has access to things like HTTP stack, file I/O, TCP and databases.
15)   What are the two arguments that async.queue takes?
The two arguments that async.queue takes
a)      Task function
b)      Concurrency value
16)   What is an event loop in Node.js ?
To process and handle external events and to convert them into callback invocations an event loop is used. So, at I/O calls, node.js can switch from one request to another .
17)   Mention the steps by which you can async in Node.js?
By following steps you can async Node.js
a)      First class functions
b)      Function composition
c)       Callback Counters
d)      Event loops
18)    What are the pros and cons of Node.js?
Pros:
a)      If your application does not have any CPU intensive computation, you can build it in Javascript top to bottom, even down to the database level if you use JSON storage object DB like MongoDB.
b)      Crawlers receive a full-rendered HTML response, which is far more SEO friendly rather than a single page application or a websockets app run on top of Node.js.
Cons:
a)       Any intensive CPU computation will block node.js responsiveness, so a threaded platform is a better approach.
b)      Using relational database with Node.js is considered less favourable
19)   How Node.js overcomes the problem of blocking of I/O operations?
Node.js solves this problem by putting the event based model at its core, using an event loop instead of threads.
20)   What is the difference between Node.js vs Ajax?
The difference between Node.js and Ajax is that, Ajax (short for Asynchronous Javascript and XML) is a client side technology, often used for updating the contents of the page without refreshing it. While,Node.js is Server Side Javascript, used for developing server software. Node.js does not execute in the browser but by the server.
21)   What are the Challenges with Node.js ?
Emphasizing on the technical side, it’s a bit of challenge in Node.js to have one process with one thread to scale up on multi core server.
22)    What does it mean “non-blocking” in node.js?
In node.js “non-blocking” means that its IO is non-blocking.  Node uses “libuv” to handle its IO in a platform-agnostic way. On windows, it uses completion ports for unix it uses epoll or kqueue etc. So, it makes a non-blocking request and upon a request, it queues it within the event loop which call the JavaScript ‘callback’ on the main JavaScript thread.
23)   What is the command that is used in node.js to import external libraries?
Command “require” is used for importing external libraries, for example, “var http=require (“http”)”.  This will load the http library and the single exported object through the http variable.
24)   Mention the framework most commonly used in node.js?
“Express” is the most common framework used in node.js
25)   What is ‘Callback’ in node.js?
Callback function is used in node.js to deal with multiple requests made to the server. Like if you have a large file which is going to take a long time for a server to read and if you don’t want a server to get engage in reading that large file while dealing with other requests, call back function is used. Call back function allows the server to deal with pending request first and call a function when it is finished.



No comments:

Post a Comment