A collection of Node JS and Golang Backend interview questions please feel free to fork and contribute to this repository
Backend Interview Questions and Answers related to Node JS , Golang/Go , Express JS , MongoDB
Click :star: if you like the project. Pull Request are highly appreciated.Node JS
Express JS
MongoDB and Mongoose
Database Engineering
Golang
Table of Contents - Node JS
| No. | Questions | | --- | --------- | | | Node JS | | 1 | What is NodeJS?| | 2 | How can you avoid callback hells?| | 3 | When are background or worker processes useful?| | 4 | Why is NodeJS Single threaded?| | 5 | Name the types of API functions in Node?| | 6 | Explain chaining in Nodejs?| | 7 | What are streams in Nodejs Explain the different types of streams present in Nodejs? | | 8 | What is package json?| | | 9 | Explain the purpose of module exports?| | 10| List down the major security implementations within Node.js?| | 11| Explain the concept of URL module?| | 12| Explain the concept of middleware in Nodejs?| | 13| Explain libuv?| | 14| List down the two arguments that async queue takes as input? | | 15| Differentiate between spawn and fork methods in Nodejs? | | 16| Explain the purpose of ExpressJS package? | | 17| Explain the usage of a buffer class in Nodejs? | | 18| How does Nodejs handle the child threads? | | 19| Explain stream in Nodejs along with its various types? | | 20| Describe the exit codes of Nodejs? | | 21| Is cryptography supported in Nodejs? | | 22| Explain the reason as to why Express app and server folder must be kept separate? | | 23| What is the role of asset module in nodejs? | | 24| What is the role of asynchooks module in nodejs? | | 25| What are buffer objects in nodejs? | | 26| What are the different ways of implementing Addons in NodeJS? | | 27| How can we spawn the child process asynchronously without blocking the Nodejs event loop? | | 28| How can we take advantage of multi-core system in Nodejs as nodejs works on single thread? | | 29| What is the datatype of console? | | 30| Which are the different console methods available? | | 31| Can node js perform cryptographic functions? | | 32| How can we read or write files in node js? | | 33| Which are the global objects in Node JS? | | 34| How can we perform asynchronous network API in Node JS? | | 35| What are the utilities of OS module in NodeJS? | | 36| Which are the areas where it is suitable to use NodeJS? | | 37| Which are the areas where it is not suitable to use NodeJS? | | 38| What Are The Key Features Of NodeJs? | | 39| Explain REPL In NodeJs? | | 40| Can you write CRUD operations in Node js without using frameworks? | | 41| Can You Create HTTP Server In Nodejs Explain The Code Used For It? | | 42| What Is The Difference Between Nodejs AJAX And JQuery? | | 43| What Is EventEmitter In NodeJs? | | 44| What Is A Childprocess Module In NodeJs? |
Node Js
- ### What is NodeJS?
- ### How can you avoid callback hells?
1.modularization: break callbacks into independent functions,
2.use a control flow library, like async.
3.use generators with Promises,
4.use async/await (note that it is only available in the latest v7 release and not in the LTS version
- ### When are background or worker processes useful?
There are lots of options for this like RabbitMQ or Kafka.
- ### Why is NodeJS Single threaded?
- ### Name the types of API functions in Node?
1.Blocking functions - In a blocking operation, all other code is blocked from executing until an I/O event that is being waited on occurs. Blocking functions execute synchronously.
2.Non-blocking functions - In a non-blocking operation, multiple I/O calls can be performed without the execution of the program being halted. Non-blocking functions execute asynchronously.
- ### Explain chaining in Nodejs?
- ### What are streams in Nodejs Explain the different types of streams present in Nodejs?
There are four types of streams.
- ### What is package json?
- ### Explain the purpose of module exports?
- ### List down the major security implementations within Nodejs?
- ### Explain the concept of URL module?
- ### Explain the concept of middleware in Nodejs?
Execute any type of code
Update or modify the request and the response objects
Finish the request-response cycle
Invoke the next middleware in the stack
- ### Explain libuv?
Full-featured event loop backed
File system events
Asynchronous file & file system operations
Asynchronous TCP & UDP sockets
Child processes
- ### List down the two arguments that async.queue takes as input?
- ### Differentiate between spawn and fork methods in Nodejs?
- ### Explain the purpose of ExpressJS package?
- ### Explain the usage of a buffer class in Nodejs?
- ### How does Nodejs handle the child threads?
- ### Explain stream in Nodejs along with its various types?
Readable: Used for reading large chunks of data from the source.
Writeable: Use for writing large chunks of data to the destination.
Duplex: Used for both the functions; read and write.
Transform: It is a duplex stream that is used for modifying the data.
- ### Describe the exit codes of Nodejs?
*Uncaught fatal exception
*Unused
*Fatal Error
*Internal Exception handler Run-time failure
*Internal JavaScript Evaluation Failure
- ### Is cryptography supported in Nodejs?
const crypto = require'crypto');
const secret = 'akerude';
const hash = crypto.createHmac('swaEdu', secret).update('Welcome to Edureka').digest('hex');
console.log(hash);
- ### Explain the reason as to why Express app and server folder must be kept separate?
*It allows testing the API in-process without having to perform the network calls
*Faster testing execution
*Getting wider coverage metrics of the code
*Allows deploying the same API under flexible and different network conditions
*Better separation of concerns and cleaner code
- ### What is the role of asset module in nodejs?
- ### What is the role of async_hooks module in nodejs?
const asynchooks = require('asynchooks');
- ### What are buffer objects in nodejs?
- ### What are the different ways of implementing Addons in NodeJS?
N-API
nan direct use of internal V8
libuv
Node.js libraries
- ### How can we spawn the child process asynchronously without blocking the Nodejs event loop?
spawnSync() function provides equivalent functionality in a synchronous manner that blocks the event loop until the spawned process either exits or is terminated
- ### How can we take advantage of multi-core system in Nodejs as nodejs works on single thread?
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) { console.log(Master ${process.pid} is running);
// Fork workers. for (let i = 0; i < numCPUs; i++) { cluster.fork(); }
cluster.on('exit', (worker, code, signal) => { console.log(worker ${worker.process.pid} died); }); } else { // Workers can share any TCP connection // In this case it is an HTTP server http.createServer((req, res) => { res.writeHead(200); res.end('hello world\n'); }).listen(8000);
console.log(Worker ${process.pid} started); } //Running Node.js will now share port 8000 between the workers: $ node server.js Master 3596 is running Worker 4324 started Worker 4520 started Worker 6056 started Worker 5644 started
- ### What is the datatype of console?
- ### Which are the different console methods available?
here are a few popular one's
1.console.clear() will clear only the output in the current terminal viewport for the Node.js binary.
2.console.error([data][, ...args]) Prints to stderr with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution
3.console.table(tabularData[, properties]) a table with the columns of the properties of tabularData (or use properties) and rows of tabularData and log it.
- ### Can node js perform cryptographic functions?
Use require('crypto') to access this module.
- ### How can we read or write files in node js?
const fs = require('fs');
There are a few methods like
fs.readFile(file, data[, options], callback)
fs.writeFile(file, data[, options], callback)
- ### Which are the global objects in Node JS?
__filename
clearImmediate(immediateObject)
clearInterval(intervalObject)
clearTimeout(timeoutObject)
console
exports
global
module
process
queueMicrotask(callback)
require()
setImmediate(callback[, ...args])
setInterval(callback, delay[, ...args])
setTimeout(callback, delay[, ...args])
TextDecoder
TextEncoder
URL
URLSearchParams
WebAssembly
- ### How can we perform asynchronous network API in Node JS?
It can be accessed using:
const net = require('net');
- ### What are the utilities of OS module in NodeJS?
const os = require('os');.
- ### Which are the areas where it is suitable to use NodeJS?
Data Streaming Applications
Data Intensive Real-time Applications (DIRT)
JSON APIs based Applications
Single Page Applications
.
- ### Which are the areas where it is not suitable to use NodeJS?
- ### What Are The Key Features Of NodeJs?
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 processing of requests within Node.js also become 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.
.
- ### Explain REPL In NodeJs?
READ - It Reads the input from the user, parses it into JavaScript data structure and then stores it in the memory.
EVAL - It Executes the data structure.
PRINT - It Prints the result obtained after evaluating the command.
LOOP - It Loops the above command until the user presses Ctrl+C two times.
.
- ### Can you write CRUD operations in Node js without using frameworks?
var http = require('http');//create a server object:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'}); // http headervar url = req.url;
if(url ==='/about'){
res.write('<h1>about us page<h1>'); //write a response
res.end(); //end the response
}else if(url ==='/contact'){
res.write('<h1>contact us page<h1>'); //write a response
res.end(); //end the response
}else{
res.write('<h1>Hello World!<h1>'); //write a response
res.end(); //end the response
}}).listen(3000, function(){
console.log("server start at port 3000"); //the server object listens on port 3000
});
.
- ### What Is The Difference Between Nodejs AJAX And JQuery?
Node.Js :
It is a server-side platform for developing client-server applications. For example, if we’ve to build an online employee management system, then we won’t do it using client-side JS. But the Node.js can certainly do it as it runs on a server similar to Apache, Django not in a browser.
AJAX (Aka Asynchronous Javascript And XML) :
It is a client-side scripting technique, primarily designed for rendering the contents of a page without refreshing it. There are a no. of large companies utilizing AJAX such as Facebook and Stack Overflow to display dynamic content.
JQuery :
It is a famous JavaScript module which complements AJAX, DOM traversal, looping and so on. This library provides many useful functions to help in JavaScript development. However, it’s not mandatory to use it but as it also manages cross-browser compatibility, so can help you produce highly maintainable web applications.
.
- ### What Is EventEmitter In NodeJs?
// Import events module
var events = require('events');
// Create an eventEmitter object var eventEmitter = new events.EventEmitter();
When an EventEmitter instance encounters an error, it emits an “error” event. When a new listener gets added, it fires a “newListener” event and when a listener gets removed, it fires a “removeListener” event.
EventEmitter provides multiple properties like “on” and “emit”. The “on” property is used to bind a function to the event and “emit” is used to fire an event. .
- ### What Is A Child_process Module In NodeJs?
The Child processes always have three streams
Node.js provides a
exec –
Table of Contents - Express JS
| No. | Questions | | --- | --------- | | | Express JS | | 1 | What is ExpressJS?| | 2 | What are some of the salient features of express?| | 3 | Explain with an example a working of a simple express app?| | 4 | Mention few properties of request parameter in express?| | 5 | How to get the name parameters in express?| | 6 | How to retrieve the get query string parameters using express? ?| | 7 | How to send a response back using express?| | 8 | How to set http response status using express?| | 9 | What are the different http status codes?| | 10 | Mention few properties of request parameter in express?| | 11 | How can you change http header value of a response?| | 12 | How to redirect to other pages server-side?| | 13 | How does routing work in express?| | 14 | What are the tasks that a middleware can do?| | 15 | What are the different types of middleware?| | 16 | How to serve static assests from express? | | 17 | How to provide file download using express?| | 18 | How to use the Response.cookie() method to manipulate your cookies?-method-to-manipulate-your-cookies)| | 19 | How to manage sessions using express?| | 20 | How to provide file download using express?| | 21 | How To Allow Cors In Expressjs Explain With An Example?|
Express Js
- ### What is ExpressJS?
Feathers: Build prototypes in minutes and production ready real-time apps in days
NestJs: A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications on top of TypeScript & JavaScript (ES6, ES7, ES8)
Sails: MVC framework for Node.js for building practical, production-ready apps.
- ### What are some of the salient features of express?
Routing: It is possible to defines a routing table in order to perform different HTTP operations.
Templates: Dynamically renders HTML Pages based on passing arguments to templates.
High Performance: Express prepare a thin layer, therefore, the performance is adequate.
Database Support: Express supports RDBMS as well as NoSQL databases.
MVC Support: Organize the web application into an MVC architecture. Manages everything from routes to rendering view and preforming HTTP request.
- ### Explain with an example a working of a simple express app?
const express = require('express')
const port = 3000
const app = express()
app.get('/', function(req, res) {
res.send('Hello World!')
})
app.listen(port, function(){
console.log('listening on port',port)
})
- ### Mention few properties of request parameter in express?
- ### How to get the name parameters in express?
// GET /user/tj
req.params.name
// => "tj"
- ### How to retrieve the get query string parameters using express?
?height=6&weight=60
//req.query.height - 6
//req.query.weight - 60
- ### How to send a response back using express?
function(req, res) {
res.send('Hello World!')
}
function(req, res) {
res.end('Hello World!')
}
function(req, res) {
res.json({title:'Hello World!'})
}
- ### How to set http response status using express?
res.status(404).send('File not found')
//if sendStatus we no need to write send method , i will pre send a few inbuilt messages upon using that
res.sendStatus(200)
// === res.status(200).send('OK')
res.sendStatus(403) // === res.status(403).send('Forbidden')
res.sendStatus(404) // === res.status(404).send('Not Found')
res.sendStatus(500) // === res.status(500).send('Internal Server Error')
- ### What are the different http status codes?
- ### Mention few properties of request parameter in express?
app.get('/', (req, res) => {
console.log(req.headers)
})
app.get('/', (req, res) => {
req.header('User-Agent')
})
Back to Top ⬆
- ### How can you change http header value of a response?
res.set('Content-Type', 'text/html')
res.type('json')
// => 'application/json'
res.type('application/json') // => 'application/json'
res.type('png') // => image/png:
Back to Top ⬆
- ### How to redirect to other pages server-side?
res.redirect('/go-there')
//it can be either a url or a path of file
res.redirect(301, '/go-there')
Back to Top ⬆
- ### How does routing work in express?
In the Hello World example we used this code
app.get('/', function(req, res) {
/ /
})
//This creates a route that maps accessing the root domain URL / using the HTTP GET method to the response we want to provide.
Back to Top ⬆
- ### What are the tasks that a middleware can do?
Execute any code.
Make changes to the request and the response objects.
End the request-response cycle.
Call the next middleware function in the stack.
- ### What are the different types of middleware?
Application-level middleware
Router-level middleware
Error-handling middleware
Built-in middleware
Third-party middleware
- ### How to serve static assests from express?
const express = require('express')
const app = express()
app.use(express.static('public'))
app.listen(3000, () => console.log('Server ready'))
- ### How to provide file download using express?
Once a user hits a route that sends a file using this method, browsers will prompt the user for download.
The Response.download() method allows you to send a file attached to the request, and the browser instead of showing it in the page, it will save it to disk.
app.get('/', (req, res) => res.download('./file.pdf'))
- ### How to use the Response.cookie() method to manipulate your cookies?
res.cookie('username', 'Adam')
This method accepts a third parameter which contains various options:
res.cookie('username', 'Adam', { domain: '.bangalore.com', path: '/administrator', secure: true })
res.cookie('username', 'Adam', { expires: new Date(Date.now() + 900000), httpOnly: true }) //clear cookie res.clearCookie('username')
The most useful parameters you can set are: | Value | Description | | ----- | ----------- | | domain | the cookie domain name| |expires|set the cookie expiration date. If missing, or 0, the cookie is a session cookie| |httpOnly|set the cookie to be accessible only by the web server. See HttpOnly| |maxAge|set the expiry time relative to the current time, expressed in milliseconds| |path|the cookie path. Defaults to /| |secure|Marks the cookie HTTPS only| |signed| set the cookie to be signed| |sameSite|Value of SameSite|
- ### How to manage sessions using express?
const express = require('express')
const session = require('express-session')
const app = express() app.use(session( 'secret': '343ji43j4n3jn4jk3n' ))
All solutions store the session id in a cookie, and keep the data server-side. The client will receive the session id in a cookie, and will send it along with every HTTP request.
We’ll reference that server-side to associate the session id with the data stored locally.
Memory is the default, it requires no special setup on your part, it’s the simplest thing but it’s meant only for development purposes.
The best choice is a memory cache like Redis, for which you need to setup its own infrastructure.
- ### How to process forms using Express?
To extract it, you will use the express.urlencoded() middleware, provided by Express:
const express = require('express') const app = express()
app.use(express.urlencoded())
Now you need to create a POST endpoint on the /submit-form route, and any data will be available on Request.body: app.post('/submit-form', (req, res) => { const username = req.body.username //... res.end() })
- ### How To Allow Cors In Expressjs Explain With An Example?
app.all('*', function(req, res, next) {
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
if ('OPTIONS' == req.method) return res.send(200);
next();
});
or you can install a package called cors ,CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.link
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
Table of Contents - MongoDB and Mongoose
| No. | Questions | | --- | --------- | | | MongoDB and Mongoose | | 1 | What is MongoDB?| | 2 | What are the difference between NoSQL and SQL| | 3 | How to establish MongoDB database connection in a node application?| | 4 | What are virtual property in mongoose| | 5 | How can we add or create our own instance methods in mongoose| | 6 | How can we add or create our own static methods in mongoose| | 7 | What are the mongoose middlewares?| | 8 | How to query data using mongoose?| | 9 | What is Population in mongoose| | 10| What is Datamasking?| | 11| What is hashing and explain how it works?| | 12| What are salts and why are they so important?| | 13| What are pepper and why are they so important?| | 14| What are JWT?| | 15| What are different authentication methods?| | 16| What are disadvantages of using session based authentication?| | 17| What are disadvantages of using jwt based authentication?|
- ### What is MongoDB?
MongoDB is written in C++
MongoDB is known to be used by the City of Chicago, Codecademy, Google Search, Foursquare, IBM, Orange S.A., The Gap, Inc., Uber, Coinbase, Sega, Barclays, HSBC, eBay, Cisco, Bosch and Urban Outfitters
- ### What are the difference between NoSQL and SQL?
- ### How to establish MongoDB database connection in a node application?
Database Connection
Next, we will add code that connects to the database.
in database.js file
const mongoose = require('mongoose'); const server = '127.0.0.1:27017'; // REPLACE WITH YOUR DB SERVER const database = 'fcc-Mail'; // REPLACE WITH YOUR DB NAME
mongoose.connect(mongodb://${server}/${database}) .then(() => { console.log('Database connection successful') }) .catch(err => { console.error('Database connection error') }) module.exports = { mongoose }
MongoDB Atlas sign up to mongosb atlas and it will help you make a connection by url, having a secret key and password
- ### What are virtual property in mongoose?
userSchema.virtual('fullName').get(function() {
return this.firstName + ' ' + this.lastName
})
userSchema.virtual('fullName').set(function(name) {
let str = name.split(' ')
this.firstName = str[0]
this.lastName = str[1]
})
const user = new User()
user.fullName = 'Thomas Anderson'
console.log(user.toJSON()) // Output model fields as JSON
console.log()
console.log(user.fullName) // Output the full name
//The code above will output the following:
{ _id: 5a7a4248550ebb9fafd898cf, firstName: 'Thomas', lastName: 'Anderson' } //Thomas Anderson
- ### How can we add or create our own instance methods in mongoose?
userSchema.methods.details = function() {
return this.username + ' - ' + this.email
}
//This method will be accessible via a model instance:
const user = new User({
username: 'user2',
email: 'user2@gmail.com'
})
- ### How can we add or create our own static methods in mongoose?
userSchema.statics.getUsers = function() {
return new Promise((resolve, reject) => {
this.find((err, docs) => {
if(err) {
console.error(err)
return reject(err)
}
resolve(docs)
})
})
}
- ### What are the mongoose middlewares?
Aggregate
Document
Model
Query
- ### How to query data using mongoose?
In this example, we are going to:
Find all users
Skip the first 100 records
Limit the results to 10 records
Sort the results by the firstName field
Select the firstName
Execute that query
User.find() // find all users .skip(100) // skip the first 100 items .limit(10) // limit to 10 items .sort({firstName: 1} // sort ascending by firstName .select({firstName: true} // select firstName only .exec() // execute the query .then(docs => { console.log(docs) }) .catch(err => { console.error(err) })
- ### What is Population in mongoose?
- ### What is Datamasking?
you can simply use $project to hide the mobile field
Or perhaps you have an extra field in your document to indicate whether the information is public or not, i.e. given documents
- ### What is hashing and explain how it works?
When the user provides a input it will be converted to a value of fixed length by a hashing function and the resulting value will be called as hashed text, and it should be always unique for different value
Back to Top ⬆
- ### What are salts and why are they so important?
They are so important as they prevent brute force attacks(Trying all possible combintaion of password) and also against rainbow table(a table containing all common hashed text and their respective passwords)
Back to Top ⬆
- ### What are pepper and why are they so important?
A pepper performs a comparable role to a salt, but while a salt is not secret (merely unique) and can be stored alongside the hashed output
A pepper is secret and must not be stored with the output. The hash and salt are usually stored in a database, but a pepper must be stored separately (e.g. in a configuration file) to prevent it from being obtained by the attacker in case of a database breach.
Where the salt only has to be long enough to be unique, a pepper has to be secure to remain secret (at least 112 bits is recommended by NIST), otherwise an attacker only needs one known entry to crack the pepper.
Finally, the pepper must be generated anew for every application it is deployed in, otherwise a breach of one application would result in lowered security of another application.
- ### What are JWT?
some scenarios where JSON Web Tokens are useful:
Authorization: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.
Information Exchange: JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed—for example, using public/private key pairs—you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn't been tampered with.

- ### What are different authentication methods?
Use API keys if you expect developers to build internal applications that don’t need to access more than a single user’s data.
Use OAuth access tokens if you want users to easily provide authorization to applications without needing to share private data or dig through developer documentation.
Use session cookies, here server is responsible for creating a session for the particular user when the user log's in, after that the id of the session is stored in a cookie on the user browser. For every request sent by the user, the cookie will be sent too, where the server can compare the session id from the cookie with the session information stored on the server so the user identity is verified.
- ### What are disadvantages of using session based authentication?
Compromised Secret Key : The best and the worst thing about JWT is that it relies on just one Key. Consider that the Key is
README truncated. View on GitHub