Node.js Interview Questions

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

What is asynchronous programming?

Asynchronous programming means we are essentially saying: "I know this function call is going to take a while, but my program doesn't want to wait around while it executes." An asynchronous model allows multiple things to happen at the same time. When you start an action, your program continues to run. When the action finishes, the program is informed and gets access to the result.

What is body-parser?

Body-parser lets us parse incoming request bodies before our handlers. It extracts information from the HTTP request body for use within your Express application, available under the req.body property. Body-parser extracts the entire body portion of an incoming request stream and exposes it on req.body.

What is "callback hell"?

"Callback hell" refers to heavily nested callbacks that have become unweildy or unreadable.

How do you create a quick Express app with express-generator?

- npm i express-generator (or yarn) - express my-express-app - npm install

How do you redirect a 404 error back to a page with Express?

/* Define fallback route */ app.use((req, res, next) => { res.status(404).json({ errorCode: 404, errorMsg: "route not found"}); });

What are the seven primitive data types in JavaScript?

1. Boolean - true or false 2. Null - no value 3. Undefined - a declared variable but hasn't been given a value 4. Number - integers, floats, etc 5. BigInt - whole numbers larger than 2^53 (larger than Number) 6. String - an array of characters i.e words 7. Symbol - a unique value that's not equal to any other value

How can we avoid "callback hell"?

1. Modularization: - The callbacks are broken out into independent functions which can be called with some parameters. 2. Promises: - Promises allow additional desirable behavior such as error propagation and chaining. 3. Generators: - Generators can resolve execution dependency between different callbacks. However, generators are much more advanced and it might be overkill to use them for this purpose.

What is the use of express.Router Class?

A Router instance is a complete middleware ad routing system; it is referred to as a "mini-app". We can use Express router to create modular, mountable route handlers. const express = require('express'); const router = express.Router( ); router.get( fn ); router.post( fn ); router.put( fn ); router.delete( fn ); module.exports = router; The Express router class was introduced with Express 4.0.

What is a URI?

A Uniform Resource Identifier (URI) is string of characters used to identify a resource on a computer network, of which the best known type is the web address or URL.

What is a URL?

A Uniform Resource Locator (URL), also called a web address, is a reference to a web resource that specifies its location on a computer network and a mechanism for retrieving it. A URL is a specific type of Uniform Resource Identifier (URI).

What is a callback function?

A callback function is a function that is passed as an argument to another function, to be "called back" at a later time, or after another function has finished executing. More complexly put: in JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions. Functions that do this are called "higher-order functions". Any function that is passed as an argument is called a "callback function".

What is closure or closures in JavaScript?

A closure (or closures) is a feature in JavaScript where an inner function has access to the outer (enclosing) function's variables. A function defined inside another function automatically gets access to the variables that are declared in the outer function.

What is a database?

A database is an organized collection of data, generally stored and accessed electronically from a computer system or server.

What is a first-class function?

A function can be treated just like any other variable: hence, functions can be passed around as parameters inside function calls to other functions. And that essentially allows us to send in functions as callback functions. These functions are first-class objects and can be: - Stored in a variable, object, or array - Passed as an argument to a function - Returned from a function

What is a Promise?

A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it's not resolved (e.g., a network error occurred). A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.

What is a server?

A server processes requests and delivers data over a network connection. It provides functionality for other programs or devices, called "clients".

What is the templating feature in Express.js?

A template engine allows us to create and render an HTML template with minimal code. At runtime, a template engine executes expressions and replaces variables with their actual values in a template file. In this way, it transforms the template into an HTML file and sent to it the client. In addition to enabling dynamic content, it also takes a significant load from the client side which may have highly variable hardware specifications, and as such, it can make applications more efficient.

What is an API?

API stands for Application Programming Interface. It is a set of subroutine definitions, communication protocols, and tools for building software. It is the part of the server that receives requests and sends responses.

What is an advantage of using express.Router( )?

An Express router defines a mini Express application, and within that mini Express application, you can, for example, deal with one particular REST API endpoint / pattern in more detail.

What is an endpoint? (API)

An endpoint is one end of a communication channel. When an API interacts with another system, the touchpoints of this communication are considered endpoints. For APIs, an endpoint can include a URL of a server or service. Each endpoint is the location from which APIs can access the resources they need to carry out their function. The place that APIs send requests and where the resource or data lives, is called an endpoint.

What is an ODM? (Object Data Model)

An object data model is a data model that treats data sets as "objects" by assigning properties and values to them.

What is CRUD, or CRUD functions?

Create, read, update, and delete (CRUD) are the four basic functions of persistent storage. Usually: Create = POST Read = GET Update = PUT Delete = DELETE

What is CORS?

Cross-origin resource sharing is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.

What is a dynamically typed language?

Dynamically typed languages infer variable types at runtime. This means once your code is run the compiler/interpreter will see your variable and its value then decide what type it is. The type is still enforced here, it just decides what the type is.

What is an error-first callback in Node.js?

Error-first callbacks in Node.js are used to pass errors and data. The very first parameter you need to pass to these functions has to be an error object while the other parameters represent the associated data. Thus you can pass the error object for checking if anything is wrong and handle it. In case there is no issue, you can just go ahead and with the subsequent arguments.

What is event-driven programming?

Event-driven programming is building our application based on and respond to events. When an event occurs, like click or keypress, we are running a callback function which is registered to the element for that event.

What is express-generator?

Express Generator is a quick scaffolding tool that will help us to quickly build up the structure for an Express application with some starting code already built and some standard middleware already included into the application.

What is Express.js?

Express.js, or simply Express, is a web application framework for Node.js. It is designed for building web applications and APIs.

What is a higher-order function(s)?

Functions that operate on other functions, either by taking them as arguments or by returning them. A higher-order function is a function that receives a function as an argument or returns the function as output.

What is an HTTP message?

HTTP messages are how data is exchanged between a server and a client. There are two types of messages: requests sent by the client to trigger an action on the server, and responses, the answer from the server.

What is the structure of an HTTP message?

HTTP requests, and responses, share similar structure and are composed of: 1. A *start-line* or *request/response line* describing the requests to be implemented, or its status of whether successful or a failure. This start-line is always a single line. 2. An optional set of *HTTP headers* specifying the request, or describing the body included in the message. 3. A *blank line* indicating all meta-information for the request have been sent. 4. An optional *body* containing data associated with the request (like content of an HTML form), or the document associated with a response. The presence of the body and its size is specified by the start-line and HTTP headers.

What is I/O?

I/O refers to input/output. It can be anything ranging from reading/writing local files to making an HTTP request to an API.

What is NoSQL or a NoSQL database?

In a NoSQL database, a "book" record is usually stored as a JSON document. For each book, the item, ISBN, Book Title, Edition Number, Author Name, and AuthorID are stored as attributes in a single document. In this model, data is optimized for intuitive development and horizontal scalability.

What is JSON?

JavaScript Object Notation is a lightweight format for storing and transporting data that is being sent from the server side to the client side or vice versa.

Why use callback functions?

JavaScript is an event driven language. This means that instead of waiting for a response before moving on, JavaScript will keep executing while listening for other events. Often we will have a task such as when we request data from other sources, such as an external API, we don't always know when our data will be served back. Callbacks are a way to make sure certain code doesn't execute until other code has already finished execution.

Is JavaScript a statically typed, dynamically typed, or weakly typed language?

JavaScript is both dynamically typed and weakly typed.

What are LTS releases of Node.js?

LTS or Long Term Support versions of Node.js that receive all the critical bug fixes along with security updates and performance improvements. These versions are supported for at least 18 months and mainly focus on stability and security.

What is middleware in Express.js?

Middleware or middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle. The next middleware function is commonly denoted by a variable named next.

What is the MVC pattern?

Model-View-Controller is an architectural pattern commonly used for developing user interfaces that divides an application into three interconnected parts. Model -> updates -> View View -> sees -> User -> User -> uses -> Controller Controller -> manipulates -> Model

What is MongoDB?

MongoDB is a document-oriented NoSQL database or database management system (DBMS). The BSON document storage and data interchange format used in MongoDB provides a binary representation of JSON-like documents.

What is Mongoose ODM?

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.

What is NPM?

NPM stands for Node Package Manager and it is a package manager for Node.js packages/modules. NPM can be used with the command-line utility in order to install various Node.js packages, manage Node.js versions and dependencies of the packages. Npmjs.com provides and hosts online repositories for Node.js packages/modules which can be easily downloaded and used in our projects.

What is typically the first argument passed to a Node.js callback handler?

Node.js core modules, as well as most community modules 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.

What is Node.js?

Node.js is a JavaScript runtime environment built on Google Chrome's V8 JavaScript Engine. Node.js came into existence when the original developers of JavaScript extended it from something you could only run in the browser to something you could run on your machine as a standalone application.

What is REPL?

REPL stands for (READ, EVAL, PRINT, LOOP) and is a computer environment similar to Shell (Unix/Linux) and command prompt. Node comes with the REPL environment when it is installed.

What is REST in NodeJS?

REST stands for REpresentational State Transfer. REST is web standards based architecture and uses HTTP Protocol and HTTP standard methods.

What does require( ) do?

Require does three things: It loads core modules that come bundled with Node.js like file system and HTTP from the Node.js API. . It loads third-party libraries like Express and Mongoose that you install from npm. It lets you require your own files and modularize the project. Require is a function, and it accepts a parameter "path" and returns the module.exports value from the "required" module

What is routing in Express.js?

Routing refers to how an application's endpoints (URIs) respond to client requests. You define routing using methods of the Express app object that correspond to HTTP methods. These routing methods specify a callback function (sometimes called "handler functions") called when the application receives a request to the specified route (endpoint) and HTTP method. app.get('/routename', (req, res)); app.post('/routename', (req, res)); app.put('/routename', (req, res)); app.delete('/routename', (req, res));

In what order do you think the following code will run? setTimeout(( ) => console.log('first'), 0); console.log('second');

Some people think that because set timeout is called with 0 (zero) it should run immediately. In fact in this specific example you will see "second" printed out before "first". JavaScript sees the setTimeout and says "Well, I should add this to my Event Table and continue executing". It will then go through the Event Table, Event Queue and wait for the Event Loop to tick in order to run.

What is a statically typed language?

Statically typed means that variable type is enforced and won't change so easily. All variables must be declared with a type.

What is HTTP or the HTTP protocol?

The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers. HTTP works as a request-response protocol between a client and server. A web browser may be the client, and an application on a computer that hosts a web site may be the server. For HTTP to work it needs a URL to be supplied to it, the Uniform Resource Locator.

What is the event loop in Node.js?

The event loop is a continuously running loop which basically picks up requests from the request queue, and then services them one at a time. This is a constantly running process that checks if the call stack is empty. Imagine it like a clock and every time it ticks it looks at the Call Stack and if it is empty it looks into the Event Queue. If there is something in the event queue that is waiting it is moved to the call stack. If not, then nothing happens. It is what allows JavaScript to use callbacks and promises.

What are the 6 phases of the event loop?

The event loop is arranged in a sequence of phases: 1. Timers: this phase executes callbacks scheduled by setTimeout( ) and setInterval( ). 2. I/O callbacks: executes almost all callbacks with the exception of close callbacks, the ones scheduled by timers, and setImmediate( ). 3. Idle, prepare: only used internally. 4. Poll: retrieve new I/O events; node will block here when appropriate. 5. Check: setImmediate( ) callbacks are invoked here.close callbacks: such as socket.on('close'). 6. Close callbacks: this phase handles any socket closures that need to be handled

What is package.json?

The package.json file in Node.js is the heart of the entire application. It is basically the manifest file that contains the metadata of the project where we define the properties of a package.

What are the start-line & HTTP headers known as? What is the payload of the HTTP message known as?

The start-line and HTTP headers of the HTTP message are collectively known as the head of the requests / responses. The payload is known as the body.

What are the 4 components to the REPL?

There are 4 components to a REPL: 1. A read function, which reads input from the keyboard 2. An eval function, which evaluates code passed to it 3. A print function, which formats and displays results 4. A loop function, which runs the three previous commands until termination

What is synchronous programming?

This means your program is executed line by line, one line at a time. Each time a function is called, program execution waits until that function returns before continuing to the next line of code, even if function execution might take a long time.

What is a weakly typed language?

Weakly typed languages allow types to be inferred as another type. For example, 1 + '2' // '12'. In JavaScript it sees you're trying to add a number with a string - an invalid operation - so it coerces your number into a string and results in the string '12'.

Consider the following code: { console.time("loop"); for (var i = 0; i < 1000000; i += 1) { // Do nothing }; console.timeEnd("loop"); } The time required to run this code in Google Chrome is considerably more than the time required to run it in Node.js. Explain why this is so, even though both use the V8 JavaScript Engine.

Within a web browser such as Chrome, declaring the variable i outside of any function's scope makes it global and therefore binds it as a property of the window object. As a result, running this code in a web browser requires repeatedly resolving the property i within the heavily populated window namespace in each iteration of the for loop. In Node.js, however, declaring any variable outside of any function's scope binds it only to the module's own scope (not the window object) which therefore makes it much easier and faster to resolve.

Why do we need authentication in our server?

Without is no control on who can perform GET/POST/PUT/DELETE operations. So which means that, if you run a server like that, then anybody can come into your server and start manipulating the information that is present within your database.

Write a function that returns a promise which will resolve after a specified time delay:

const wait = (time) => { new Promise((resolve) => setTimeout(resolve, time)); }; wait(3000).then(( ) => console.log('Hello!')); // 'Hello!'

How else can we also write the following: module.exports = area;

exports.area = ( fn );

Write a program that will take in a string and check if it is a palindrome.

isPalindrome = (str) => { let flag = false; const newStr = str.split(" ").join("").toLowerCase(); let revStr = ""; for (let i = newStr.length - 1; i >= 0; i--) { revStr += newStr[i]; }; if (revStr === newStr) { flag = true; }; return flag; };


Kaugnay na mga set ng pag-aaral

RESPONDERSAFETY TIM: Incident Command & Management

View Set

Monitor and back up Azure resources

View Set

Lesson 22 (How Populations Evolve #1)

View Set

MKTG 3553Chapter 9-10-11-12-13-14-15

View Set

American Sports History Chapters 1-4

View Set

ATI Ch.23 Gastrointestinal Structural and Inflammatory Disorders

View Set