Q-1. What Is Node.Js?
Answer.
Node.js is a JavaScript runtime or platform which is built on Google Chrome’s JavaScript v8 engine. This runtime allows executing the JavaScript code on any machine outside a browser (this means that it is the server that executes the Javascript and not the browser).
Node.js is single-threaded, that employs a concurrency model based on an event loop. It doesn’t block the execution instead registers a callback which allows the application to continue. It means Node.js can handle concurrent operations without creating multiple threads of execution so can scale pretty well.
It uses JavaScript along with C/C++ for things like interacting with the filesystem, starting up HTTP or TCP servers and so on. Due to it’s extensively fast growing community and NPM, Node.js has become a very popular, open source and cross-platform app. It allows developing very fast and scalable network app that can run on Microsoft Windows, Linux, or OS X.
Following are the areas where it’s perfect to use Node.js.
§ I/O bound Applications
§ Data Streaming Applications
§ Data Intensive Real-time Applications (DIRT)
§ JSON APIs based Applications
§ Single Page Applications
At the same time, it’s not suitable for heavy applications involving more of CPU usage.
Q-2. What Are the Key Features Of Node.Js?
Answer.
Let’s look at some of the key features of Node.js.
§ Asynchronous event driven IO helps concurrent request handling – All APIs of Node.js are asynchronous. This feature means that if a Node receives a request for some Input/Output operation, it will execute that operation in the background and continue with the processing of other requests. Thus, it will not wait for the response from the previous requests.
§ Fast in Code execution – Node.js uses the V8 JavaScript Runtime engine, the one which is used by Google Chrome. Node has a wrapper over the JavaScript engine which makes the runtime engine much faster and hence processing of requests within Node.js also become faster.
§ Single Threaded but Highly Scalable – Node.js uses a single thread model for event looping. The response from these events may or may not reach the server immediately. However, this does not block other operations. Thus making Node.js highly scalable. Traditional servers create limited threads to handle requests while Node.js creates a single thread that provides service to much larger numbers of such requests.
§ Node.js library uses JavaScript – This is another important aspect of Node.js from the developer’s point of view. The majority of developers are already well-versed in JavaScript. Hence, development in Node.js becomes easier for a developer who knows JavaScript.
§ There is an Active and vibrant community for the Node.js framework – The active community always keeps the framework updated with the latest trends in the web development.
§ No Buffering – Node.js applications never buffer any data. They simply output the data in chunks.
Q-3. Explain How Do We Decide, When to Use Node.Js And When Not To Use It?
Answer.
When Should We Use Node.Js?
It’s ideal to use Node.js for developing streaming or event-based real-time applications that require less CPU usage such as.
§ Chat applications.
§ Game servers.
Node.js is good for fast and high-performance servers, that face the need to handle thousands of user requests simultaneously.
Good for A Collaborative Environment.
It is suitable for environments where multiple people work together. For example, they post their documents, modify them by doing check-out and check-in of these documents.
Node.js supports such situations by creating an event loop for every change made to the document. The “Event loop” feature of Node.js enables it to handle multiple events simultaneously without getting blocked.
Advertisement Servers.
Here again, we have servers that handle thousands of requests for downloading advertisements from a central host. And Node.js is an ideal solution to handle such tasks.
Streaming Servers.
Another ideal scenario to use Node.js is for multimedia streaming servers where clients fire requests towards the server to download different multimedia contents from it.
To summarize, it’s good to use Node.js, when you need high levels of concurrency but less amount of dedicated CPU time.
Last but not the least, since Node.js uses JavaScript internally, so it fits best for building client-side applications that also use JavaScript.
When to Not Use Node.Js?
However, we can use Node.js for a variety of applications. But it is a single threaded framework, so we should not use it for cases where the application requires long processing time. If the server is doing some calculation, it won’t be able to process any other requests. Hence, Node.js is best when processing needs less dedicated CPU time.
Q-5. Explain How Does Node.Js Work?
Answer.
A Node.js application creates a single thread on its invocation. Whenever Node.js receives a request, it first completes its processing before moving on to the next request.
Node.js works asynchronously by using the event loop and callback functions, to handle multiple requests coming in parallel. An Event Loop is a functionality which handles and processes all your external events and just converts them to a callback function. It invokes all the event handlers at a proper time. Thus, lots of work is done on the back-end, while processing a single request, so that the new incoming request doesn’t have to wait if the processing is not complete.
While processing a request, Node.js attaches a callback function to it and moves it to the back-end. Now, whenever its response is ready, an event is called which triggers the associated callback function to send this response.
Let’s Take an Example of A Grocery Delivery.
Usually, the delivery boy goes to each and every house to deliver the packet. Node.js works in the same way and processes one request at a time. The problem arises when any one house is not open. The delivery boy can’t stop at one house and wait till it gets opened up. What he will do next, is to call the owner and ask him to call when the house is open. Meanwhile, he is going to other places for delivery. Node.js works in the same way. It doesn’t wait for the processing of the request to complete (house is open). Instead, it attaches a callback function (call from the owner of the house) to it. Whenever the processing of a request completes (the house is open), an event gets called, which triggers the associated callback function to send the response.
To summarize, Node.js does not process the requests in parallel. Instead, all the back-end processes like, I/O operations, heavy computation tasks, that take a lot of time to execute, run in parallel with other requests.
Q-6. Explain REPL In Node.Js?
Answer.
The REPL stands for “Read Eval Print Loop”. It is a simple program that accepts the commands, evaluates them, and finally prints the results. REPL provides an environment similar to that of Unix/Linux shell or a window console, in which we can enter the command and the system, in turn, responds with the output. REPL performs the following tasks.
§ READ
§ It Reads the input from the user, parses it into JavaScript data structure and then stores it in the memory.
§ EVAL
§ It Executes the data structure.
§ It Prints the result obtained after evaluating the command.
§ LOOP
§ It Loops the above command until the user presses Ctrl+C two times.
Q-7. Is Node.Js Entirely Based on A Single-Thread?
Answer.
Yes, it’s true that Node.js processes all requests on a single thread. But it’s just a part of the theory behind Node.js design. In fact, more than the single thread mechanism, it makes use of events and callbacks to handle a large no. of requests asynchronously.
Moreover, Node.js has an optimized design which utilizes both JavaScript and C++ to guarantee maximum performance. JavaScript executes at the server-side by Google Chrome v8 engine. And the C++ lib UV library takes care of the non-sequential I/O via background workers.
To explain it practically, let’s assume there are 100s of requests lined up in Node.js queue. As per design, the main thread of Node.js event loop will receive all of them and forwards to background workers for execution. Once the workers finish processing requests, the registered callbacks get notified on event loop thread to pass the result back to the user.
Q-8. How to Get Post Data In Node.Js?
Answer.
Following is the code snippet to fetch Post Data using Node.js.
app.use(express.bodyParser());
app.post('/', function(request, response){
console.log(request.body.user);
});
Q-9. How to Make Post Request In Node.Js?
Answer.
Following code snippet can be used to make a Post Request in Node.js.
var request = require('request');
request.post(
'http://www.example.com/action',
{ form: { key: 'value' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
Q-10. What Is Callback in Node.Js?
Answer.
We may call “callback” as an asynchronous equivalent for a function. Node.js makes heavy use of callbacks and triggers it at the completion of a given task. All the APIs of Node.js are written in such a way that they support callbacks.
For example, suppose we have a function to read a file, as soon as it starts reading the file, Node.js return the control immediately to the execution environment so that the next instruction can be executed. Once file read operation is complete, it will call the callback function and pass the contents of the file as its arguments. Hence, there is no blocking or wait, due to File I/O. This functionality makes Node.js as highly scalable, using it processes a high number of requests without waiting for any function to return the expected result.
Q-11. What Is Callback Hell?
Answer.
Initially, you may praise Callback after learning about it. Callback hell is heavily nested callbacks which make the code unreadable and difficult to maintain.
Let’s see the following code example.
downloadPhoto('http://coolcats.com/cat.gif', displayPhoto)
function displayPhoto (error, photo) {
if (error) console.error('Download error!', error)
else console.log('Download finished', photo)
}
console.log('Download started')
In this scenario, Node.js first declares the “displayPhoto” function. After that, it calls the “downloadPhoto” function and pass the “displayPhoto” function as its callback. Finally, the code prints ‘Download started’ on the console. The “displayPhoto” will be executed only after “downloadPhoto” completes the execution of all its tasks.
Q-12. How To Avoid Callback Hell In Node.Js?
Answer.
Node.js internally uses a single-threaded event loop to process queued events. But this approach may lead to blocking the entire process if there is a task running longer than expected.
Node.js addresses this problem by incorporating callbacks also known as higher-order functions. So whenever a long-running process finishes its execution, it triggers the callback associated. With this approach, it can allow the code execution to continue past the long-running task.
However, the above solution looks extremely promising. But sometimes, it could lead to complex and unreadable code. More the no. of callbacks, longer the chain of returning callbacks would be. Just see the below example.
With such an unprecedented complexity, it’s hard to debug the code and can cause you a whole lot of time. There are four solutions which can address the callback hell problem.
1. Make Your Program Modular.
It proposes to split the logic into smaller modules. And then join them together from the main module to achieve the desired result.
2. Use Async Mechanism.
It is a widely used Node.js module which provides a sequential flow of execution.
The async module has <async.waterfall> API which passes data from one operation to other using the next callback.
Another async API <async.map> allows iterating over a list of items in parallel and calls back with another list of results.
With the async approach, the caller’s callback gets called only once. The caller here is the main method using the async module.
3. Use Promises Mechanism.
Promises give an alternate way to write async code. They either return the result of execution or the error/exception. Implementing promises requires the use of <.then()> function which waits for the promise object to return. It takes two optional arguments, both functions. Depending on the state of the promise only one of them will get called. The first function call proceeds if the promise gets fulfilled. However, if the promise gets rejected, then the second function will get called.
4. Use Generators.
Generators are lightweight routines, they make a function wait and resume via the yield keyword. Generator functions uses a special syntax <function* ()>. They can also suspend and resume asynchronous operations using constructs such as promises or <thunks> and turn a synchronous code into asynchronous.
Q-13. Can You Create HTTP Server in Node.Js, Explain the Code Used For It?
Answer.
Yes, we can create HTTP Server in Node.js. We can use the <http-server> command to do so.
Following is the sample code.
var http = require('http');
var requestListener = function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Welcome Viewers\n');
}
var server = http.createServer(requestListener);
server.listen(8080); // The port where you want to start with.
Q-14. What Is the Difference Between Node.Js, AJAX, And JQuery?
Answer.
The one common trait between Node.js, AJAX, and jQuery is that all of them are the advanced implementation of JavaScript. However, they serve completely different purposes.
Node.Js –
It is a server-side platform for developing client-server applications. For example, if we’ve to build an online employee management system, then we won’t do it using client-side JS. But the Node.js can certainly do it as it runs on a server similar to Apache, Django not in a browser.
AJAX (Aka Asynchronous JavaScript and XML) –
It is a client-side scripting technique, primarily designed for rendering the contents of a page without refreshing it. There are a no. of large companies utilizing AJAX such as Facebook and Stack Overflow to display dynamic content.
JQuery –
It is a famous JavaScript module which complements AJAX, DOM traversal, looping and so on. This library provides many useful functions to help in JavaScript development. However, it’s not mandatory to use it but as it also manages cross-browser compatibility, so can help you produce highly maintainable web applications.
Q-15. What Are Globals In Node.Js?
Answer.
There are three keywords in Node.js which constitute as Globals. These are Global, Process, and Buffer.
Global.
The Global keyword represents the global namespace object. It acts as a container for all other <global> objects. If we type <console.log(global)>, it’ll print out all of them.
An important point to note about the global objects is that not all of them are in the global scope, some of them fall in the module scope. So, it’s wise to declare them without using the var keyword or add them to Global object.
Variables declared using the var keyword become local to the module whereas those declared without it get subscribed to the global object.
Process.
It is also one of the global objects but includes additional functionality to turn a synchronous function into an async callback. There is no boundation to access it from anywhere in the code. It is the instance of the EventEmitter class. And each node application object is an instance of the Process object.
It primarily gives back the information about the application or the environment.
§ <process.execPath> – to get the execution path of the Node app.
§ <process.Version> – to get the Node version currently running.
§ <process.platform> – to get the server platform.
Some of the other useful Process methods are as follows.
§ <process.memoryUsage> – To know the memory used by Node application.
§ <process.NextTick> – To attach a callback function that will get called during the next loop. It can cause a delay in executing a function.
Buffer.
The Buffer is a class in Node.js to handle binary data. It is similar to a list of integers but stores as a raw memory outside the V8 heap.
We can convert JavaScript string objects into Buffers. But it requires mentioning the encoding type explicitly.
§ <ascii> – Specifies 7-bit ASCII data.
§ <utf8> – Represents multibyte encoded Unicode char set.
§ <utf16le> – Indicates 2 or 4 bytes, little endian encoded Unicode chars.
§ <base64> – Used for Base64 string encoding.
§ <hex> – Encodes each byte as two hexadecimal chars.
Here is the syntax to use the Buffer class.
> var buffer = new Buffer(string, [encoding]);
The above command will allocate a new buffer holding the string with <utf8> as the default encoding. However, if you like to write a <string> to an existing buffer object, then use the following line of code.
> buffer.write(string)
This class also offers other methods like <readInt8> and <writeUInt8> that allows read/write from various types of data to the buffer.
Q-16. How to Load HTML in Node.Js?
Answer.
To load HTML in Node.js we have to change the “Content-type” in the HTML code from text/plain to text/html.
Let’s see an example where we have created a static file in web server.
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200);
response.write(file, "binary");
response.end();
});
Now we will modify this code to load an HTML page instead of plain text.
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/html"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200, {"Content-Type": "text/html"});
response.write(file);
response.end();
});
Q-17. What Is EventEmitter In Node.Js?
Answer.
Events module in Node.js allows us to create and handle custom events. The Event module contains “EventEmitter” class which can be used to raise and handle custom events. It is accessible via the following code.
// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
When an EventEmitter instance encounters an error, it emits an “error” event. When a new listener gets added, it fires a “newListener” event and when a listener gets removed, it fires a “removeListener” event.
EventEmitter provides multiple properties like “on” and “emit”. The “on” property is used to bind a function to the event and “emit” is used to fire an event.
Q-18. How many types of Streams are present in Node.Js?
Answer.
Stream in Node.js are objects that allow reading data from a source or writing data to a specific destination in a continuous fashion. In Node.js, there are four types of streams.
§ <Readable> – This is the Stream to be used for reading operation.
§ <Writable> – It facilitates the write operation.
§ <Duplex> – This Stream can be used for both the read and write operations.
§ <Transform> – It is a form of a duplex Stream, which performs the computations based on the available input.
All the Streams, discussed above are an instance of an “EventEmitter” class. The event thrown by the Stream varies with time. Some of the commonly used events are as follows.
§ <data> – This event gets fired when there is data available for reading.
§ <end> – The Stream fires this event when there is no more data to read.
§ <error> – This event gets fired when there is any error in reading or writing data.
§ <finish> – It fires this event after it has flushed all the data to the underlying system.
Q-19. List and explain the important REPL commands?
Answer.
Following is the list of some of the most commonly used REPL commands.
§ <.help> – It displays help for all the commands.
§ <tab Keys> – It displays the list of all the available commands.
§ <Up/Down Keys> – Its use is to determine what command was executed in REPL previously.
§ <.save filename> – Save the current REPL session to a file.
§ <.load filename> – To Load the specified file in the current REPL session.
§ <ctrl + c> – used to Terminate the current command.
§ <ctrl + c (twice)> – To Exit from the REPL.
§ <ctrl + d> – This command preforms Exit from the REPL.
§ <.break> – It leads Exiting from multiline expression.
§ <.clear> – Exit from multiline expression.
Q-20. What Is NPM In Node.Js?
Answer.
NPM stands for Node Package Manager. It provides following two main functionalities.
§ It works as an Online repository for node.js packages/modules which are present at <nodejs.org>.
§ It works as Command line utility to install packages, do version management and dependency management of Node.js packages.
NPM comes bundled along with Node.js installable. We can verify its version using the following command-
$ npm --version
NPM helps to install any Node.js module using the following command.
$ npm install <Module Name>
For example, following is the command to install a famous Node.js web framework module called express-
$ npm install express
Q-21. What is the Global installation of dependencies?
Answer.
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 cannot be imported using require() in the Node application directly.
To install a Node project globally use -g flag as.
C:\Nodejs_WorkSpace>npm install express -g
Q-22. What is the Local installation of dependencies?
Answer.
By default, NPM installs any dependency in the local mode. It means that the package gets installed in “node_modules” directory which is present in the same folder, where Node application is placed. Locally deployed packages are accessible via require(). Following is the syntax to install a Node project locally.
C:\Nodejs_WorkSpace>npm install express
Q-23. What is Package.Json? Who Uses It?
Answer.
What Is <Package.Json>?
§ It is a plain JSON (JavaScript Object Notation) text file which contains all metadata information about Node.js Project or application.
§ This file should be present in the root directory of every Node.js Package or Module to describe its metadata in JSON format.
§ The file is named as “package” because Node.js platform treats every feature as a separate component. Node.js calls these as Package or Module.
Who Use It?
§ NPM (Node Package Manager) uses <package.json> file. It includes details of the Node.js application or package. This file contains a no. of different directives or elements. These directives guide NPM, about how to handle a module or package.
Q-24. Does Node.Js Support Multi-Core Platforms? And Is It Capable Of Utilizing All The Cores?
Answer.
Yes, Node.js would run on a multi-core system without any issue. But it is by default a single-threaded application, so it can’t completely utilize the multi-core system.
However, Node.js can facilitate deployment on multi-core systems where it does use the additional hardware. It packages with a Cluster module which is capable of starting multiple Node.js worker processes that will share the same port.
Q-25. Which Is the First Argument Usually Passed to A Node.Js Callback Handler?
Answer.
Node.js core modules follow a standard signature for its callback handlers and usually the first argument is an optional error object. And if there is no error, then the argument defaults to null or undefined.
Here is a sample signature for the Node.js callback handler.
function callback(error, results) {
// Check for errors before handling results.
if ( error ) {
// Handle error and return.
}
// No error, continue with callback handling.
}
Q-26. What is Chaining Process in Node.Js?
Answer.
It’s an approach to connect the output of one stream to the input of another stream, thus creating a chain of multiple stream operations.
Q-27. How To Create A Custom Directive In AngularJS?
Answer.
To create a custom directive, we have to first register it with the application object by calling the <directive> function. While invoking the <register> method of <directive>, we need to give the name of the function implementing the logic for that directive.
For example, in the below code, we have created a copyright directive which returns a copyright text.
app.directive('myCopyRight', function ()
{
return
{
template: '@CopyRight MyDomain.com '
};
});
Note – A custom directive should follow the camel case format as shown above.
Q-28. What Is A Child_process Module In Node.Js?
Answer.
Node.js supports the creation of child processes to help in parallel processing along with the event-driven model.
The Child processes always have three streams <child.stdin>, child.stdout, and child.stderr. The <stdio> stream of the parent process shares the streams of the child process.
Node.js provides a <child_process> module which supports following three methods to create a child process.
§ exec – <child_process.exec> method runs a command in a shell/console and buffers the output.
§ spawn – <child_process.spawn> launches a new process with a given command.
§ fork – <child_process.fork> is a special case of the spawn() method to create child processes.
Q-29. What are the Different Custom Directive Types in AngularJS?
Answer.
AngularJS supports a no. of different directives which also depend on the level we want to restrict them.
So, in all, there are four different kinds of custom directives.
§ Element Directives (E)
§ Attribute Directives (A)
§ CSS Class Directives (C)
§ Comment Directives (M)
Q-30. What is a Control Flow Function? What Are the steps Does It Execute?
Answer.
It is a generic piece of code which runs in between several asynchronous function calls is known as control flow function.
It executes the following steps.
§ Control the order of execution.
§ Collect data.
§ Limit concurrency.
§ Call the next step in the program.
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.
Error-first callbacks are used to pass errors and data. The first argument is always an error object that the programmer has to check if something went wrong. Additional arguments are used to pass data.
fs.readFile(filePath, function(err, data) {
if (err) {
//handle the error
}
// use the data object
});
How does this question help?
The answer for this question will get you some insight on whether the candidate has some basic knowledge on how async operations work in Node.
To do so you have more options:
· modularization: break callbacks into independent functions
· use Promises
· use yield
with Generators and/or Promises
How does this question help?
The answer for this question may vary a lot, depending on how up-to-date one is, how closely is she following the latest developments, be it ES6, ES7 or just a new control flow library.
Trick question! You should not try to listen with Node on port 80 (in Unix-like systems) - to do so you would need superuser rights, but it is not a good idea to run your application with it.
Still, if you want to have your Node.js application listen on port 80, here is what you can do. Run the application on any port above 1024, then put a reverse proxy like nginx in front of it.
How does this question help?
This question helps you to find out whether the one you are talking to has any experience operating Node applications.
TL;DR:
It is a magical place filled with unicorns and rainbows - Trevor Norris
Node.js runs using a single thread, at least from a Node.js developer's point of view. Under the hood Node.js uses many threads through libuv.
Every I/O requires a callback - once they are done they are pushed onto the event loop for execution. If you need a more detailed explanation, I suggest viewing this video:
How does this question help?
This will give you an insight on how deep someone's knowledge on Node is, if she/he knows what libuv is.
You have plenty of options to do so:
· JSLint by Douglas Crockford
· JSHint
· ESLint
· JSCS
These tools are really helpful when developing code in teams, to enforce a given style guide and to catch common errors using static analysis.
How does this question help?
With this you will have some idea if the one you are talking to has any experience on how large scale JavaScript applications should be developed.
Operation errors are not bugs, but problems with the system, like request timeoutor hardware failure.
On the other hand programmer errors are actual bugs.
How does this question help?
As this question has little to do with Node, you can get a more general idea on the candidate's level.
This command locks down the versions of a package's dependencies so that you can control exactly which versions of each dependency will be used when your package is installed. - npmjs.com
It is useful when you are deploying your Node.js applications - with it you can be sure which versions of your dependencies are going to be deployed.
How does this question help?
This questions helps to get a deeper understanding on the candidate's knowledge of both the npm cli and Node.js operational best practices.
Stubs are functions/programs that simulate the behaviours of components/modules. Stubs provide canned answers to function calls made during test cases. Also, you can assert on with what these stubs were called.
A use-case can be a file read, when you do not want to read an actual file:
var fs = require('fs');
var readFileStub = sinon.stub(fs, 'readFile', function (path, cb) {
return cb(null, 'filecontent');
});
expect(readFileStub).to.be.called;
readFileStub.restore();
How does this question help?
This question helps to get some clue on one's testing knowledge - if she/he don't know what stubs are you can ask how she/he does unit testing.
A test pyramid describes that when writings test cases there should be a lot more low-level unit tests than high level end-to-end tests.
When talking about HTTP APIs, it may come down to this:
· a lot of low-level unit tests for your models
· less integration tests, where your test how your models interact with each other
· a lot less acceptance tests, where you test the actual HTTP endpoints
How does this question help?
How experienced your candidate in testing? This question will tell a lot about that, especially if she/he can go into the details of each level, and for each level what kind of tools can be used.
There is no right answer for this. The goal here is to understand how deeply one knows the framework she/he uses, if can reason about it, knows the pros, cons.
As you may already guessed, we are not huge fans of these type of questions. Instead we do believe in small, real-life problems, solved together. During these you will get a very good understanding of how one thinks. But not just that. You will know if she/he is a good fit for your team, as you have to solve something together.
When we are hiring (and we are always hiring) we usually look for a combination of the following:
· cultural fit
o transparency
o self-improvement
o bias towards clarity
o do things smarter than harder
· skill and expertise
1. What is node.js
Short Answer
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.
Long Answer
Node.js is a server-side technology that’s based on Google’s V8 JavaScript engine. It’s a highly scalable system that uses asynchronous, event-driven I/O (input/output), rather than threads or separate processes. It’s ideal for web applications that are frequently accessed but computationally simple.
If you’re using a traditional web server, such as Apache, each time a web resource is requested, Apache creates a separate thread or invokes a new process in order to handle the request. Even though Apache responds quickly to requests, and cleans up after the request has been satisfied, this approach can still tie up a lot of resources. A popular web application is going to have serious performance issues.
Node, on the other hand, doesn’t create a new thread or process for every request. Instead, it listens for specific events, and when the event happens, responds accordingly. Node doesn’t block any other request while waiting for the event functionality to complete, and events are handled—first come, first served—in a relatively uncomplicated event loop. Node applications are created with JavaScript (or an alternative language that compiles to JavaScript). The JavaScript is the same as you’d use in your client-side applications. However, unlike JavaScript in a browser, with Node you have to set up a development environment.
Node can be installed in a Unix/Linux, Mac OS, or Windows environment. This chapter will walk you through setting up a development environment for Node in Windows 7 and Linux (Ubuntu). Installation on a Mac should be similar to installation on Linux. I’ll also cover any requirements or preparation you need to take before installing the application. Once your development environment is operational, I’ll demonstrate a basic Node application and walk you through the important bit—the event loop I mentioned earlier.
2. How node.js works
Short Answer
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.
Long Answer
NodeJS is built on top of V8, Google’s Javascript engine that also powers the Chrome browser, which sported the fastest Javascript execution speeds and pretty much put Javascript performance right up in front when it came to comparing browsers, turning speed into a major marketing for browsers.
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.
5. Where can we use node.js?
Node.js shines in real-time web applications employing push technology over web sockets. It 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?
It provides an easy way to build scalable network programs a) Easy to install and run locally b) Generally fast c) Great concurrency d) Asynchronous everything e) Almost never blocks f) Unified programming language and data type
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?
Control the order of execution -> Collect data -> Limit concurrency -> 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?
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 : First class functions -> Function composition -> Callback Counters -> Event loops
18. What are the pros and cons of Node.js?
· 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.
· 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 favorable.
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.
26. How Does Node Differ From Other Frameworks?
The major difference between Node and other server-side technologies is Node’s use of a single thread and asynchronous architecture. Many other server-side technologies are multi-threaded and synchronous, meaning that threads can be blocked while waiting for replies from the database. Each request creates a new thread from a limited pool based on system RAM usage. Node’s asynchronous design allows it to handle a large number of concurrent connections with high throughput on a single-thread, which makes it highly scalable. Node is not meant as a replacement for other technology stacks, but it can provide scalability and increased performance to applications which fit its purpose. Some examples of application types which can benefit from using Node are REST APIs, Chat applications and Real-Time Tracking applications (Brokerage trading dashboards, real-time user statistics, etc.) Node’s homepage describes it as “lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.” The applications above fit that description well and can take advantage of Node’s features.
27. In which language Node.js is written?
C,C++, javaScript.
28. How to get Post Data in Node.js?
app.use(express.bodyParser(); app.post('/', function(request, response){ console.log(request.body.user); });
29. How to make Post request in Node.js?
var request = require('request');
request.post('http://www.example.com/action',
{ form: { key: 'value' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
30. What is callback hell?
Callback hell refers to heavily nested callbacks that have become unreadable
Process.on('uncaughtException', function(err)
{
console.log('Caught exception: ' + err);
});
32. Can you explain how Nodejs works
It uses Google V8 Javascript engine to execute code. It contains built-in asynchronous I/O library for file, socket and HTTP communication. Node.js encapsulates libuv to handle asynchronous events.
33. Can you explain what is Globals in Nodejs?
Global, Process and Buffer are combinedly termed as Globals.
Global : Its a global namespace object
Process : Its also a global object but it provides essential functionality to transform a synchronous function into a asynchronous
callback. Buffer : Raw data is stored in instances of the Buffer class.
34. What is the Use of underscore in Nodejs?
To access the last expression, we have to use the (_) underscore/underline character.
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.
36. 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.
37. Mention the framework most commonly used in node.js?
“Express” is the most common framework used 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.
39. Can you create Http Server in Nodejs, explain with code?
Yes, we can create Http Server in Nodejs. We can use http-server command to do so.
Code :
1
2
3
4
5
6
7
8
var http = require('http');
var requestListener = function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello You\n');
}
var server = http.createServer(requestListener);
server.listen(8080); // The port where you want to start with.
40. How to load HTML in Nodejs?
To load HTML in Nodejs we have to change the Content-type from text/plain to text/html.
The difference between Node.js and Ajax is that Ajax is a client side technology whereas Nodejs is server side technology. Ajax is used for updating the contents of the page without refreshing it whereas Nodejs is used for developing server software. Nodejs is executed by the server whereas Ajax is executed by the browser.
42. Can you explain the difference between readFile vs createReadStream in Nodejs?
readFile - It will read the file completely into memory before making it available to the User.
createReadStream - It will read the file in chunks of the size which is specified before hand.
43. What are Event listeners ?
Event listeners are similar to call back functions but are associated with some event. For example when a server listens to http request on a given port a event will be generated and to specify http server has received and will invoke corresponding event listener. Basically, Event listener's are also call backs for a corresponding event.
Node JS has built in event's and built in event listeners. Node JS also provides functionality to create Custom events and Custom Event listeners.
44. How is Node JS application's work is scheduled on to the Event queue ?
Node JS Applications can schedule work to event queue by passing a Call back function in the following ways.
45. What is typically the first argument passed to a Node.js callback handler?
Node.js core modules, as well as most of the community-published ones, follow a pattern whereby the first argument to any callback handler is an optional error object. If there is no error, the argument will be null or undefined.
A typical callback handler could therefore perform error handling as follows:
function callback(err, results) {
// usually we'll check for the error before handling results
if(err) {
// handle error somehow and return
}
// no error, perform standard callback handling
}
Since Node.js is by default a single thread application, it will run on a single processor core and will not take full advantage of multiple core resources. However, Node.js provides support for deployment on multiple-core systems, to take greater advantage of the hardware. The Cluster module is one of the core Node.js modules and it allows running multiple Node.js worker processes that will share the same port.
47. How does Node.js handle child threads?
Consider the following JavaScript code:
console.log("first");
setTimeout(function() {
console.log("second");
}, 0);
console.log("third");
The output will be:
first
third
second
48. What are the benefits of using Node.js?
Following are main benefits of using Node.js
49. 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.
50. Can we evaluate simple expression using Node REPL ?
Incorrect. The correct answer is : A) Yes
51. 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.
52. What is npm?
npm stands for Node Package Manager. npm provides following two main functionalities:
53. What is global installation of dependencies?
Globally installed packages/dependencies are stored in /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
54. 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
55. How to check the already installed dependencies which are globally installed using npm?
Use the following command:
C:\Nodejs_WorkSpace>npm ls -g
56. 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
57. Name some of the attributes of package.json?
Following are the attributes of Package.json
58. How to uninstall a dependency using npm?
Use following command to uninstall a module.
C:\Nodejs_WorkSpace>npm uninstall dependency-name
59. How to uninstall a dependency using npm?
Use following command to uninstall a module.
C:\Nodejs_WorkSpace>npm uninstall dependency-name
60. 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
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.
62. 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.
63. How Node prevents blocking code?
By providing callback function. Callback function gets called whenever corresponding event triggered.
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.
65. What is Event Emmitter?
EventEmitter class lies in events module. It is accessibly via following syntax:
1
2
3
4
//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 emit. on property is used to bind a function with the event and emit is used to fire an event.
66. What is purpose of Buffer class in Node?
Buffer class is a global class and can be accessed in application without importing buffer module. A Buffer is a kind of an array of integers and corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.
Piping is a mechanism to connect output of one stream to another stream. It is normally used to get data from one stream and to pass output of that stream to another stream. There is no limit on piping operations. Consider the above example, where we've read test.txt using readerStream and write test1.txt using writerStream. Now we'll use the piping to simplify our operation or reading from one file and writing to another fil
68. Which module is used for file based operations?
fs module is used for file based operations.
1
var fs = require("fs")
69. Which module is used for buffer based operations?
Buffer module is used for buffer based operations.
1
var buffer = require("buffer")
70. Which module is used for web based operations?
http module is used for web based operations.
1
var http = require("http")
71. fs module provides both synchronous as well as asynchronous methods.
Correct!
72. 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.
73. Name some of the flags used in read/write operation on files.
Flags for read/write operations are following:
74. What are streams?
Streams are objects that let you read data from a source or write data to a destination in continous fashion.
75. How many types of streams are present in Node.
In Node.js, there are four types of streams:
76. Name some of the events fired by streams.
Each type of Stream is an EventEmitter instance and throws several events at different instance of times. For example, some of the commonly used events are:
77. 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.
78. How will you open a file using Node?
Following is the syntax of the method to open a file in asynchronous mode:
1
fs.open(path, flags[, mode], callback)
Parameters
Here is the description of the parameters used:
79. How will you read a file using Node?
Following is the syntax of one of the methods to read from a file:
1
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:
80. How will you write a file using Node?
Following is the syntax of one of the methods to write into a file:
1
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:
81. 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:
82. 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:
83. 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:
84. 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:
85. 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:
86. 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:
87. 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:
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.
89. What is the purpose of __dirname variable?
The __dirname represents the name of the directory that the currently executing script resides in.
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.
91. 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.
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).
93. What is the purpose of console object?
console object is used to Used to print information on stdout and stderr.
94. What is the purpose of process object?
Process object is used to get information on current process. Provides multiple events related to process activities.
95. What is the advantage of using node.js?
Advantage
What is Node.js?
Node.js is a web application framework built on Google Chrome's JavaScript EngineV8EngineV8Engine.
Node.js comes with runtime environment on which a Javascript based script can be interpreted and executed ItisanalogustoJVMtoJAVAbytecodeItisanalogustoJVMtoJAVAbytecode. 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
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.
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.
Is it free to use Node.js?
Yes! Node.js is released under the MIT license and is free to use.
Is Node a single threaded application?
Yes! Node uses a single threaded model with event looping.
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.
Can we evaluate simple expression using Node REPL
Yes.
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.
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
>
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.
What is global installation of dependencies?
Globally installed packages/dependencies are stored in <user-directory>/npm directory. Such dependencies can be used in CLI CommandLineInterfaceCommandLineInterface 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
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
How to check the already installed dependencies which are globally installed using npm?
Use the following command:
C:\Nodejs_WorkSpace>npm ls -g
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
How to uninstall a dependency using npm?
Use following command to uninstall a module.
C:\Nodejs_WorkSpace>npm uninstall dependency-name
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
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.
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.
How Node prevents blocking code?
By providing callback function. Callback function gets called whenever corresponding event triggered.
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.
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 emit. on property is used to bind a function with the event and emit is used to fire an event.
What is purpose of Buffer class in Node?
Buffer class is a global class and can be accessed in application without importing buffer module. A Buffer is a kind of an array of integers and corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.
What is Piping in Node?
Piping is a mechanism to connect output of one stream to another stream. It is normally used to get data from one stream and to pass output of that stream to another stream. There is no limit on piping operations. Consider the above example, where we've read test.txt using readerStream and write test1.txt using writerStream. Now we'll use the piping to simplify our operation or reading from one file and writing to another file.
Which module is used for file based operations?
fs module is used for file based operations.
var fs = require("fs")
Which module is used for buffer based operations?
buffer module is used for buffer based operations.
var buffer = require("buffer")
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.
true.
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 ifitdoesnotexistifitdoesnotexist or truncated ifitexistsifitexists.
· wx - Like 'w' but fails if path exists.
· w+ - Open file for reading and writing. The file is created ifitdoesnotexistifitdoesnotexist or truncated ifitexistsifitexists.
· 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.
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.
Name some of the events fired by streams.
Each type of Stream is an EventEmitter instance and throws several events at different instance of times. For example, some of the commonly used events are:
· data - This event is fired when there is data is available to read.
· end - This event is fired when there is no more data to read.
· error - This event is fired when there is any error receiving or writing data.
· finish - This event is fired when all data has been flushed to underlying system
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.
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)
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 permissionandstickybitspermissionandstickybits, 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,fderr,fd.
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.
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,buffererr,bytesRead,buffer.
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.
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.
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)
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)
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,statserr,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)
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)
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)
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)
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)
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,fileserr,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 setTimeoutcb,mscb,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 clearTimeouttt 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 setIntervalcb,mscb,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 clearIntervaltt.
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.