NodeJS – Questions & Answers

1. What is node.js?      

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?

NodeJS works on a V8 environment, it is a virtual machine that utilizes JavaScript as its scripting language.

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.

4. 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.

5. What does event-driven programming means?

In event-driven programming, flow of the program is determined by events. 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.

6. What are two different types of functions in Node.js?

a) Asynchronous, non-blocking functions

b) Synchronous, blocking functions

7. What is control flow function?  

A generic piece of code which runs in between several asynchronous function calls is known as control flow function.

8. 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.

9. 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.

10. Using the event loop what are the tasks that should be done asynchronously?  

a) I/O operations

b) Heavy computation

c) Anything requiring blocking

11. 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.

12. 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.

13. What is ‘callback’?

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

14. Difference between Node.js and Ajax?

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.

15. 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.

NodeJS has built in event’s and built in event listeners. NodeJS also provides functionality to create Custom events and Custom Event listeners.

16. How is NodeJS application’s work is scheduled on to the Event queue?  

NodeJS Applications can schedule work to event queue by passing a Call back function in the following ways

  • During a call to Blocking IO
  • Built in Event Listener to a Built in Event
  • Custom Event Listeners to Custom Events
  • Process.nextTick option to schedule work to be picked up in the next cycle of the event loop
  • Using Timers to schedule work after some delayed period of time

17 . What are the 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.

18. 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.

19. 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.

All npm packages contain a file, usually in the project root, called package.json.
package.json file holds various metadata relevant to the project.
This file is used to give information to npm that allows it to identify the project as well as handle the project’s dependencies.
It can also contain other metadata like description, version, license and configuration data.

20. Command for installing the node utilities like Gulp, Bower and Nodemon in the system?

Npm install –g gulp bower nodemon The –g flag in the above command ensure that the node utilites is available globally for any project

21. What is Nodemon?

Nodemon is a utility that monitors for any changes in the development source files and automatically restart the server whenever a code change happens.  Nodemon will watch the files in the directory and if there is a change in the files, it will automatically restart node application.  It does not look for any changes made in the source code of development.  By issuing the below command we install nodemon

npm install nodemon –g  here g swich is globally available in the system

22. What is Gulp?

Gulp is a tool that helps you out with several tasks when it comes to web development. It’s often used to do front end tasks like:

  • Spinning up a web server
  • Reloading the browser automatically whenever a file is saved
  • Using preprocessors like Sass or LESS
  • Optimizing assets like CSS, JavaScript, and images

Gulp is a build system that employs Node.js’s streams to implement an asynchronous source-destination approach to automation. Everything is written in JavaScript, so it is easy for anyone with intermediate coding knowledge to get started. A Gulp build process consists of a collection of watchers and tasks.

23. What is Browserify?

Browserify is a development tool that allows us to write node.js-style modules that compile for use in the browser. Just like node, we write our modules in separate files, exporting external methods and properties using the module.exports and exportsvariables. We can even require other modules using the require function, and if we omit the relative path it’ll resolve to the module in the node_modules directory.

24. What are the pros and cons of Node.js?  

Pros

  • Asynchronous event driven IO helps concurrent request handling.
  • Uses JavaScript, which is easy to learn.
  • 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.
  • 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

  • Any intensive CPU computation will block node.js responsiveness, so a threaded platform is a better approach.
  • Using relational database with Node.js is considered less favorable.
  • Every time using a callback end up with tons of nested callbacks.
  • Node.js is not suited for CPU-intensive tasks. It is suited for I/O stuff only (like web servers).

25. Blocking vs Non-Blocking

Blocking Vs Non-Blocking

26. 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.

27. What are most common REPL Commands?

ctrl + c ? terminate the current command.
ctrl + c twice ? terminate the Node REPL.
ctrl + d ? terminate the REPL.
Up/Down Keys ? see command history.
tab Keys ? list of current commands.
.help ? list of all commands.
.break ? exit from multiline expression.
.clear ? exit from multiline expression.
.save filename ? save the current session to a file.
.load filename ? load file content in Node REPL session.

28. What is the difference between local and global module in Node.js?

When we Installed a module locally, then we need to use require() to use module.
When we Installed a module globally, then we need’t to use require() to use module.

29. Give example Blocking vs non-blocking in node.js?

Create a file with “input.txt” with content “Hello I am here.”;

Blocking code

var fs = require(“fs”);

var data = fs.readFileSync(‘input.txt’);

console.log(data.toString());

console.log(“End of script”);
Output
Hello I am here.
End of script

Non-Blocking code

var fs = require(“fs”);

fs.readFile(‘input.txt’, function (err, data) {

if (err) return console.error(err);

console.log(data.toString());

});

console.log(“End of script”);

Output
End of script
Hello I am here.

Please feel free to write your comments, suggestions or corrections.

 

 

Advertisements