NodeJS Interview Questions
What is NodeJS
NodeJS is a free, open source and cross platform javascript runtime. It is used to build server side applications. It can be used in I/O intensive application.
Explain features of NodeJS
Following are the features of NodeJS-
- Single threaded - Multiple code does not run at the same time
- Non blocking and Asynchronous - Pending operation does not block the process for execution of other operations
- Cross platform - NodeJS runs on multiple platforms like Windows, Unix, Linux, MacOS etc
- Fast - Built with Chrome's V8 JS engine which executes the code quickly
- No Buffering – NodeJS applications never buffer any data. They simply output the data in chunks.
What is I/O in NodeJS?
I/O or Input Output defines how NodeJS handles different operations, requests. It handles interaction between programs like file handling, processing network requests, database connections etc.
List real world NodeJS applications
- Video streaming
- Chat applications
- Realtime collaboration
- Single page applications
What is NPM?
NPM stands for Node Package Manager. NPM is a tool to manage NodeJS packages. It is a repository where developers can store or access various libraries. It is a default package manager for NodeJS.
NPM currently holds around 2 million packages which is available for free.
Official site: npm
How to check the node and npm versions?
To check versions type below commands in your terminal-
> node -v
v18.16.0
> npm -v
9.5.1
How to create a NodeJS project
We can create a NodeJS project using following command-
npm init
What is package.json?
Package.json is a file which is necessary for NodeJS projects. It hold information like meta data, dependencies, scripts etc.
Below is the example of package.json file
{
"name": "project name",
"version": "1.0.0",
"dependencies": {
"package1": "version",
"package2": "version"
},
"scripts": {
"start": "node index.js"
}
}
How to install a package in NodeJS?
We can install a package using following command-
npm i --save package-name1 package-name2
To save a package as dev dependency, use following command-
npm i --save-dev package-name1 package-name2
Explain Express.js
Express.js is a middleware used to handle API requests in NodeJS application. Using Express.js, request and response objects can be processed. It is used to create routes for performing CRUD operations, error handling, logging etc.
E.g.
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
How to read a file in NodeJS?
File can be read using following ways-
- Asynchronous-
const fs = require('node:fs');
fs.readFile('/path/to/file', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
- Synchronous-
const fs = require('node:fs');
try {
const data = fs.readFileSync('/path/to/file', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
How to write to a file in NodeJS?
Files can be written using following ways-
- Asynchronous-
const fs = require('node:fs');
const text = 'Hello World';
fs.writeFile('/path/to/file.txt', text, err => {
if (err) {
console.error(err);
}
console.log('Successfully written');
});
- Synchronous-
const fs = require('node:fs');
const text = 'Hello World';
try {
fs.writeFileSync('/path/to/file.txt', text);
console.log('Successfully written');
} catch (err) {
console.error(err);
}
Explain Event Loop
Event loop in NodeJS is used to handle asynchronous operations. It executes events and constantly checks their progress. Once the event is is progress, it moves to another event and puts it in event loop. Once the event is completed, event loop executes the associated callback.
Explain modules in NodeJS
Modules are a piece of code or functionality that can be used throughout the application. There are two types of modules-
- Built-in Modules - available as part of nodejs installation
- Custom Modules - built as per application usage
How to use a module?
A module is imported using require function and can be used as follows-
var path = require('path');
How to build a custom module?
Custom module is created as follows-
// greet.js
export.greet = function (name) {
return `Hello ${name}`
}
To use this module in another file, require()
function is used
const greet = require('./greet');
console.log(greet('John')); // Hello John
List few built-in NodeJS modules
- http
- https
- path
- fs
- dns
- os
- assert
What is JWT?
JWT stands for JSON Web Token is a standard used to token based authentication. It is used to securely transmit JSON objects between clients and servers.
With JWT, tokens are created with secret key and required payloads. Now, tokens are shared between parties for authentication and authorization purposes.
JWT is available in npm and it can be installed as follows-
npm i jsonwebtoken
Token can be created using sign
method.
const jwt = require('jsonwebtoken');
const token = jwt.sign({ email: 'mail@email.com' }, '<secret-key>');
What is REPL?
REPL stands for Read Eval Print Loop. It is an interactive shell to run JavaScript code in a NodeJS environment. It is used for debugging and running Javascript code in terminal.
To start REPL, type node
in your terminal. Now, we can execute JavaScript commands in the terminal.
> node
> 2+3
5
> console.log('Hello')
Hello
Explain Buffer Class
A buffer is used as a storage for raw binary data. Binary class helps in managing and processing binary data. Buffer represents a memory which is not resizable.
A buffer using size can be created as follows-
const buffer = Buffer.alloc(200);
A buffer using data can be created as follows-
const text = 'some text';
const buffer = Buffer.from(text, 'utf8');
What is EventEmitter?
EventEmitter is a class available as part of NodeJS package events
.
It allows to create and manage custom events.
With EventEmitter class, you can emit and listen to events.
E.g.
const events = require('events');
const emitter = new events.EventEmitter();
// listener1 function
function listener1() {
// code to handle event1
}
// event1 is handled with listener1
emitter.on('event1', listener1)
// event1 is emitted
emitter.emit('event1');