Tuesday, May 14, 2019

Nodejs viva question and answer


https://www.youtube.com/watch?v=OHYjxMoG5XU (very very inportnat)

difference between async.series and async.parallel

async.series invokes your functions serially (waiting for each preceding one to finish before starting next). async.parallel will launch them all simultaneously (or whatever passes for simultaneous in one-thread land, anyway).



--------------------------------------------
https://www.designcise.com/web/tutorial/whats-the-difference-between-promise-all-and-promise-allsettled-in-javascript

Promise.all():

Promise.all() resolves only when all given promises resolve, and will reject immediately if any of the promises reject (or non-promises throw an error). It is useful in cases when you have interdependent tasks, where it makes sense to reject immediately upon any of them rejecting.

Promise.allSettled():

Promise.allSettled() resolves when all of the given promises have either fulfilled or rejected. Unlike Promise.all(), it does not immediately reject upon any of the promises rejecting, instead it waits for all promises to complete, even if some of them fail. Therefore, it is useful in cases when you have multiple asynchronous tasks that are not interdependent, where you may want to know the result of each promise.

----------------------------------

nodejs debuging

-- use console.log ,      --instapact, vs code provide builting debuging 

---------

Event module 

https://www.tutorialspoint.com/nodejs/nodejs_event_emitter.htm

----------------------------
Error handling
https://www.toptal.com/nodejs/node-js-error-handling

Up to this point, we mostly discussed dealing with operational errors. How about programmer errors? The best way to deal with these errors is to crash immediately and restart gracefully with an automatic restarter like PM2—the reason being that programmer errors are unexpected, as they are actual bugs that might cause the application to end up in a wrong state and behave in an unexpected way.





What is Node.js? Where can you use it?  
Node.js is a JavaScript runtime platform built on Chrome's V8 JavaScript engine.
-- video streaming sites
-- real time application (chatting)
-- General-purpose applications and Distributed systems.
Features of Node.js
Asynchronous and Event DrivenAll APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call.
  • It is generally fast
  • It almost never blocks
  • It offers a unified programming language and data type
  • Everything is asynchronous


Where to Use Node.js?

Following are the areas where Node.js is proving itself as a perfect technology partner.
  • I/O bound/intensive Applications (An application that reads and/or writes a large amount of data)
  • Data Streaming Applications ()
  • Data Intensive Real-time Applications (DIRT)
  • JSON APIs based Applications
  • Single Page Applications

Where Not to Use Node.js?

It is not advisable to use Node.js for CPU Bound/intensive applications.

Is Node.js a framework?

No, it's an environment, and back-end frameworks run within it. Popular ones include Express.js (or simply Express) for HTTP servers and Socket.IO for WebSocket servers.

Is Node.js a programming language?

No, the ".js" means that the programming language you use with Node.js is JavaScript (or anything that can transpile to it, like TypeScript, Haxe, or CoffeeScript.)

What is the difference between Node.js and Angular/AngularJS?

Node.js executes JavaScript code in its environment on the server, whereas Angular is a JavaScript framework that gets executed on the client (i.e. within a web browser.)

Why is Node.js Single-threaded?

Node.js is single-threaded for async processing.
-- For single thread, more performance and scalability

By doing async processing on a single-thread under typical web loads, more performance and scalability can be achieved as opposed to the typical thread-based implementation.


Explain callback in Node.js.

A callback function is called at the completion of a given task. This allows other code to be run in the meantime and prevents any blocking.  Being an asynchronous platform, Node.js heavily relies on callback. All APIs of Node are written to support callbacks.

-- library or functions are asynchoronus so, sometime we need to do some task after getting response. that we send callback function with custom code to execute.

What are the functionalities of NPM in Node.js?

NPM (Node package Manager) provides two functionalities:
  • Online repository for Node.js packages
  • Command line utility for installing packages, version management and dependency management of Node.js packages

What are Globals in Node.js?

Three keywords in Node.js constitute as Globals. These are:
  • Global – it represents the Global namespace object and acts as a container for all other <global> objects.
  • Process – It is one of the global objects but can turn a synchronous function into an async callback. It can be accessed from anywhere in the code and it primarily gives back information about the application or the environment. 
  • Buffer – it is a class in Node.js to handle binary data. 
  • console - console.log, console.info. console.info
  • settimeout
  • settimeinterval
  • __filename
  • __dirname

     


 What are “streams” in Node.js

Streams are objects that let you read data from a source or write data to a destination in continuous fashion. 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.
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 the data has been flushed to underlying system.


Node.js - Utility Modules

 There are several utility modules available in Node.js module library. These modules are very common and are frequently used while developing any Node based application.

OS Module
Provides basic operating-system related utility functions.
Path Module
Provides utilities for handling and transforming file paths.
Net Module
Provides both servers and clients as streams. Acts as a network wrapper.
DNS Module
Provides functions to do actual DNS lookup as well as to use underlying operating system name resolution functionalities.
Domain Module
Provides ways to handle multiple different I/O operations as a single group.


Can you access DOM in node?
No, you cannot access DOM in node.

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.

What is global installation of dependencies?

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











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.
 
 

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.
 
 Which module is used for file based operations? 
fs module is used for file based operations.
var fs = require("fs")
 
buffer module is used for buffer based operations.
var buffer = require("buffer")
http module is used for web based operations.
var http = require("http")
 
 
What is Piping in Node? 

Piping is a mechanism to connect output of one stream to another stream. 
 
 
 









Streams are objects that let you read data from a source or write data to a destination in continuous fashion.

 
 
 
 

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.
 
 

 It shows the latest version of the package that is available.

 npm view <package-name> version
 
 

Interview Questions

Interview questions for Node.js engineers fall into three categories:

  1. General questions: Here, the interviewer should verify common tech knowledge for senior engineers.
  2. JavaScript questions: Node.js is a JavaScript runtime environment, so developers should have a deep understanding of the JavaScript programming language itself. We maintain a community-driven list of interview questions that can be used here.
  3. Node.js questions: Subjects related to the platform itself.

We’ll focus here on platform-related questions for senior developers that can help determine whether a candidate is a great Node.js engineer.

Q: What are three ways to handle asynchronous operations in Node.js? Describe their pros and cons.

There are three primary, built-in approaches for handling async operations: callbacks, promises, and async/await.

Callbacks are the oldest method. It’s best to avoid them, as they have a couple of anti-patterns, like callback hell (also known as the “Pyramid of Doom”). However, they are quite widely used in old projects and libraries.

Promises are a native feature of ECMAScript 6 (ES6, sometimes called ES2015)—supported fully since Node.js 6.17, and partially as far back as Node.js 0.12. They have additional methods that make them more powerful and flexible than callbacks.

Async/await is the newest native approach to deal with asynchronous operations. It’s the best one from a code structure perspective but doesn’t have such a wide range of built-in features as promises do.

Developers should definitely understand and use promises and async/await. It’s even better if they’re experienced with other tools for handling async operations, like bluebird and observables; if they’re being hired for an existing project that uses these extensively, this may be more of a requirement than a nice-to-have.

Red flag: The developer still defaults to callbacks and doesn’t know (or care) about promises and async/await.

Q: How should Node.js developers handle errors in asynchronous functions?

As a follow-up to the answers of the previous question, each approach to asynchronous code has its own way of handling errors.

To handle errors using callbacks, there is the quite well-known error-first convention:

fetchUsers(url, (err, data) => {

  if (err) {

    // handle error 

  } else {

    // operate upon data

  }

});

The idea is that an error is always passed as the first argument of a callback function so it can be handled in a consistent way.

In contrast, promises have a special catch handler to process errors:

fetchUsers(url)

  .then(data => {

    // operate upon data

  })

  .catch(err => {

    // handle error 

  });

To handle errors when using async/await, developers can use a simple try-catch block:

async main() {

  try {

    const data = await fetchUsers(url);

    // operate upon data

  } catch (err) {

    // handle error 

  }

}

Node.js developer candidates should be able to describe the examples above.

Red flags: The developer has little or no experience with handling errors from callbacks, promises, and async/await. (That said, since callbacks aren’t recommended anyway, knowledge of callback error handling would be less important for a greenfield project.)

Q: What are some Node.js frameworks for building web applications? Describe their pros and cons.

Frameworks are almost always a necessity with Node.js. It is quite unlikely for engineers to use pure Node.js built-ins to build web servers, as there are widespread and robust solutions for that, and it simply doesn’t make sense to reinvent the wheel.

Express.js is one of the most popular Node.js frameworks for web applications. Its long-term support is quite good, and it has a lot of commonly needed routing and middleware features, extending Node.js functionality to make it more flexible and powerful.

Nest.js is essentially an upgrade to Express.js that uses TypeScript, a modern language that’s a strict syntactical superset of JavaScript. It provides developers with the ability to write better, more structured, and less error-prone code.

Hapi.jsKoa.jsMeteor, and Sails.js are other web application frameworks for Node.js a candidate might mention.

In the table below, some pros and cons of each of them are listed.

FrameworkAdvantagesDisadvantages
Express.js
  • Simple, flexible, scalable
  • Wide functionality
  • Easy to learn
  • Easy to customize
  • Used by a broad audience
  • Well-documented
  • Performant
  • Does not use TypeScript
  • Difficult to maintain
Nest.js
  • Uses TypeScript
  • Built on top of Express.js
  • Has a well-structured architecture, similar to the Angular framework
  • Used by a broad audience
  • Has built-in modules for popular technologies like GraphQL, microservices, and WebSockets
  • Relatively new, so some functionality from Express.js is not in place
Hapi.js
  • Plugin system, allowing for easier maintenance
  • Profound control of request handling
  • Does not use TypeScript
  • Small audience
  • Performance is lacking
Koa.js
  • Good user experience
  • Lightweight
  • Clean and readable async code
  • Does not use TypeScript
  • Small audience
  • No built-in middleware

Red flag: A Node.js developer with weak or absent knowledge of web application frameworks. A definite exception here would be if they have strong knowledge in one particular framework—particularly Express.js, since it’s practically a de-facto standard and even the foundation of some of the other frameworks.

Q: What are the two main ways to scale an application? Is there anything specifically to Node.js in how you would approach them?

This question helps determine whether a developer has experience with building large applications. Node.js apps can be scaled horizontally and vertically.

Horizontal: Node.js can be cloned and distributed across multiple servers, or across CPU nodes within one server. There are solutions in a place like PM2 that help to distribute load across nodes within a server, or AWS Load Balancer to help with multi-server scaling.

Vertical: This means CPU and memory can be increased on the same node/server—nothing Node.js-specific.

Red flag: The developer doesn’t have knowledge of, or experience in, scaling.

Q: How do developers test a Node.js application?

There are three main types of testing: unit, integration, and end-to-end.

  • Unit testing means testing individual units/components of an application. It’s the lowest level of testing, the purpose of which is to verify if small pieces of code work properly in isolation.
  • Integration testing is the next level of testing, which intends to make sure that separate modules work together accurately.
  • End-to-end testing is the highest level of the testing hierarchy, which verifies that both client and server work properly together.

Quite often, developers need to use stubs and spies to mock third-party modules or API calls. They are crucial during testing as they prevent accessing real data, and simplify testing itself.

There are different packages for Node.js that help with testing, including Mocha, Chai, and Jest. Developers should be familiar with at least one—preferably with the one (hopefully) already in use, in the case of an existing project.

At the very least, a candidate should understand the difference between testing types.

Red flag: The developer has no experience with unit, integration, or end-to-end testing.

Q: How can Node.js developers make sure that project dependencies are secure?

A Node.js app may become insecure because of the npm packages in use. There are a few rules developers should follow to keep an application safe:

  1. Check packages themselves. It’s worth validating the package’s author, its GitHub stars, opened/closed issues comparison, weekly downloads, number of releases, etc.
  2. Use the npm audit command. It allows getting a list of packages’ known vulnerabilities. Running npm audit fix would automatically install compatible updates to vulnerable dependencies. It also executes by default during npm install.
  3. Use npm outdated to verify if any installed packages are obsolete.

Dedicated Node.js developers will take care of vulnerabilities by staying on top of such issues continuously as part of the development process.

Red flag: The developer blanketly ignores or doesn’t care about vulnerability warning messages.

Q: What are global objects in Node.js? Describe them.

Node.js has two types of global objects: global and pseudo-global.

Global objects are those which are available in the global scope. There are also built-in objects that are accessible in the global scope as well—those that are part of the JavaScript language itself.

The most-used global objects are:

  1. console, a Node.js module used to print to stdout and stderr
  2. global, a global namespace object. In browsers, the top-level scope is the global scope, but Node.js is different. A method/variable should be put in the global object to be accessible in every module.
  3. process, a Node.js module allowing interaction with Node.js’ running process
  4. Built-in functions, like setTimeout()setImmediate(), and setInterval()

By contrast, pseudo-global objects exist in the module scope. Pseudo-globals include:

  1. __dirname, the directory name of the current module
  2. __filename, the file name of the current module
  3. moduleexports, and module.exports, which are part of Node.js module system
  4. require(), a built-in function which allows the import of other modules

Red flag: The developer has no experience with, or does not understand the differences between, types of globals.

How to Hire Node.js Developers Most Effectively

The process of hiring a great Node.js developer is more than just interviewing with platform-related questions. It implies validating both technical and soft skills.

Out of all of the important topics that the soft skills review covers, a fundamental first step before searching is asking oneself, “Why am I looking for a skilled Node.js developer in the first place?” Be it igniting the existing development team with extra developer power, or mentoring peers and leading a technical transformation and excellence process, or kick-starting an MVP—answering this question greatly helps to define the values, traits, and experience of the ideal candidate.

Notwithstanding the goals of the soft skills review, the technical part comes into play at all times. Node.js development is an expertise that has some standard sets of tooling, patterns, and integral parts that are used over and over. The more experience a Node.js developer has using them for solving various problems and combining them in different ways, the more valuable such a developer becomes for development teams.

There’s definite value in the simple process of going through the fundamental topics of modern Node.js development flow, such as databases, third-party tools, DevOps, and the Node.js platform itself. Hearing answers to some pivotal development-, JavaScript-, and Node.js-specific questions can shed light on whether the developer is indeed as experienced and skilled as will be required for the goals that will be put before them.

 
 
 
 
Reference:
  1. https://www.journaldev.com/7462/node-js-architecture-single-threaded-event-loop (good for understanding nodje architechture)
  2. https://www.simplilearn.com/node-js-interview-questions-and-answers-article
  3.  https://career.guru99.com/top-25-interview-questions-on-node-js/
  4. https://www.tutorialspoint.com/nodejs/nodejs_interview_questions.htm (VVI for viva questin preperation)
  5. https://www.tutorialspoint.com/nodejs/nodejs_mock_test.htm?min=1&max=25 (important) 
  6.  http://upwork-test.pe.hu/node-js
  7. http://bodesktestanswers2013.blogspot.com/2016/06/upwork-nodejs-test-2016.html 
  8. https://codeburst.io/all-about-core-nodejs-part-1-b9f4b0a83278(Please read the doc for buffer : You want to change from one string encoding to another.)


/************************************************************

https://medium.com/@madasamy/15-javascript-concepts-that-every-nodejs-programmer-must-to-know-6894f5157cb7

(To understand apply/call/bind in javascript)

/*****************************************



No comments:

Post a Comment

Autoboxing and Unboxing

  Autoboxing  is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper cl...