Node.js basic Interview Question and answers
Q. What is Node.js?
Node.js is an open-source server-side runtime environment built on Chrome's V8 JavaScript engine. It provides an event-driven, non-blocking (asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side applications using JavaScript.
Q. What is Node.js Process Model?
Node.js runs in a single process and the application code runs in a single thread and thereby needs fewer resources than other platforms.
All the user requests to your web application will be handled by a single thread and all the I/O work or long running job is performed asynchronously for a particular request.
So, this single thread doesn't have to wait for the request to complete and is free to handle the next request. When asynchronous I/O work completes then it processes the request further and sends the response.
Q. What are 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 the processing of requests within Node.js also becomes 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. Explain how does Node.js work?
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.
Q. How to create a simple server in Node.js that returns Hello World?
Step 01: Create a project directory
mkdir myapp
cd myapp
Step 02: Initialize project and link it to npm
npm init -y
This creates a package.json
file in your myapp folder. The file contains references for all npm packages you have downloaded to your project. The command will prompt you to enter a number of things. You can enter your way through all of them EXCEPT this one:
entry point: (index.js)
Rename this to:
app.js
Step 03: Install Express in the myapp directory
npm install express --save
ExpressJs is very famous NodeJs Framework which is used to create fast and
Scalable project with very less line of code.
Step 04: app.js
/**
* Express.js
*/
const express = require('express');
const app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('App listening on port 3000!');
});
Step 05: Run the app
node app.js
⚝ Try this example on CodeSandbox
Q. Explain the concept of URL module in Node.js?
The URL module in Node.js splits up a web address into readable parts. Use require()
to include the module. Then parse an address with the url.parse()
method, and it will return a URL object with each part of the address as properties.
Example:
/**
* URL Module in Node.js
*/
const url = require('url');
const adr = 'http://localhost:8080/default.htm?year=2022&month=september';
const q = url.parse(adr, true);
console.log(q.host); // localhost:8080
console.log(q.pathname); // "/default.htm"
console.log(q.search); // "?year=2022&month=september"
const qdata = q.query; // { year: 2022, month: 'september' }
console.log(qdata.month); // "september"
Q. What are the data types in Node.js?
Just like JS, there are two categories of data types in Node: Primitives and Objects.
1. Primitives:
- String
- Number
- BigInt
- Boolean
- Undefined
- Null
- Symbol
2. Objects:
- Function
- Array
- Buffer
Q. Explain String data type in Node.js?
Strings in Node.js are sequences of Unicode characters. Strings can be wrapped in single or double quotation marks. Javascript provide many functions to operate on string, like indexOf(), split(), substr(), length.
String functions:
Function | Description |
---|---|
charAt() | It is useful to find a specific character present in a string. |
Concat() | It is useful to concat more than one string. |
indexOf() | It is useful to get the index of a specified character or a part of the string. |
Match() | It is useful to match multiple strings. |
Split() | It is useful to split the string and return an array of string. |
Join() | It is useful to join the array of strings and those are separated by comma (,) operator. |
Example:
/**
* String Data Type
*/
const str1 = "Hello";
const str2 = 'World';
console.log("Concat Using (+) :" , (str1 + ' ' + str2));
console.log("Concat Using Function :" , (str1.concat(str2)));
Q. Explain the Number data type in Node.js?
The number data type in Node.js is 64 bits floating point number both positive and negative. The parseInt() and parseFloat() functions are used to convert to a number, if it fails to convert into a number then it returns NaN
.
Example:
/**
* Number Data Type
*/
// Example 01:
const num1 = 10;
const num2 = 20;
console.log(`sum: ${num1 + num2}`);
// Example 02:
console.log(parseInt("32")); // 32
console.log(parseFloat("8.24")); // 8.24
console.log(parseInt("234.12345")); // 234
console.log(parseFloat("10")); // 10
// Example 03:
console.log(isFinite(10/5)); // true
console.log(isFinite(10/0)); // false
// Example 04:
console.log(5 / 0); // Infinity
console.log(-5 / 0); // -Infinity
Q. Explain BigInt data type in Node.js?
A BigInt value, also sometimes just called a BigInt, is a bigint primitive, created by appending n to the end of an integer literal, or by calling the BigInt() function ( without the new operator ) and giving it an integer value or string value.
Example:
/**
* BigInt Data Type
*/
const maxSafeInteger = 99n; // This is a BigInt
const num2 = BigInt('99'); // This is equivalent
const num3 = BigInt(99); // Also works
typeof 1n === 'bigint' // true
typeof BigInt('1') === 'bigint' // true
Q. Explain Boolean data type in Node.js?
A boolean data type is a data type that has one of two possible values, either true or false. In programming, it is used in logical representation or to control program structure.
The boolean() function is used to convert any data type to a boolean value. According to the rules, false, 0, NaN, null, undefined, and empty strings evaluate to false and other values evaluate to true.
Example:
/**
* Boolean Data Type
*/
// Example 01:
const isValid = true;
console.log(isValid); // true
// Example 02:
console.log(true && true); // true
console.log(true && false); // false
console.log(true || false); // true
console.log(false || false); // false
console.log(!true); // false
console.log(!false); // true
Q. Explain Undefined
and Null
data type in Node.js?
In node.js, if a variable is defined without assigning any value, then that will take undefined as value. If we assign a null value to the variable, then the value of the variable becomes null.
Example:
/**
* NULL and UNDEFINED Data Type
*/
let x;
console.log(x); // undefined
let y = null;
console.log(y); // null
Q. Explain Symbol data type in Node.js?
A symbol is an immutable primitive value that is unique. It's a very peculiar data type. Once you create a symbol, its value is kept private and for internal use.
Example:
/**
* Symbol Data Type
*/
const NAME = Symbol()
const person = {
[NAME]: 'Script Revision'
}
person[NAME] // 'Script Revision'
Q. Explain Buffer data type in Node.js?
Node.js includes an additional data type called Buffer ( not available in the browser's JavaScript ). Buffer is mainly used to store binary data while reading from a file or receiving packets over the network.
Example:
/**
* Buffer Data Type
*/
let b = new Buffer(10000);
let str = " ";
b.write(str);
console.log( str.length ); // 25
console.log( b.length ); // 10000
0 Comments