Node JS MCQs
Q.1. How can you handle errors when writing to a file in Node.js?
A. Use a try-catch block
B. Ignore errors
C. Reopen the file
D. Restart Node.js
Q.2 What should you do if fs.readFile returns an error?
A. Retry reading the file
B. Check the file path
C. Change file permissions
D. Reboot the system
Q.3 How do you check if a file exists in Node.js?
A. fs.existsSync(‘example.txt’)
B. fs.checkFile(‘example.txt’)
C. fs.exists(‘example.txt’)
D. fs.fileExists(‘example.txt’)
Q.4 What is the output of fs.readFileSync(‘example.txt’)?
A. A promise
B. A buffer
C. An error
D. A string
Q.5 How do you read a file named ‘example.txt’ in Node.js?
A. fs.readFile(‘example.txt’, callback)
B. fs.open(‘example.txt’, callback)
C. fs.read(‘example.txt’, callback)
D. fs.readFile(‘example.txt’)
Q.6 Which method is used to append data to a file in Node.js?
A. fs.appendFile
B. fs.writeFile
C. fs.addData
D. fs.insert
Q.7 How can you read the content of a directory in Node.js?
A. fs.readDir
B. fs.readDirectory
C. fs.readdir
D. fs.read
Q.8 Which method is used to open a file in Node.js?
A. fs.readFile
B. fs.open
C. fs.write
D. fs.unlink
Q.9 What does the fs.unlink method do in Node.js?
A. Reads a file
B. Writes to a file
C. Deletes a file
D. Renames a file
Q.10 Which method writes data to a file in Node.js?
A. fs.readFile
B. fs.writeFile
C. fs.open
D. fs.appendFile
Q.11 Which method reads the content of a file in Node.js?
A. fs.readFile
B. fs.open
C. fs.read
D. fs.write
Q.12 An application crashes with “Error: Cannot find module”.
What should be checked?
A. Node version
B. Module installation
C. Network connection
D. Disk space
Q.13 What should you do if a module is not found?
A. Reinstall Node.js
B. Check module spelling
C. Use a different IDE
D. Update npm
Q.14 How do you make a function available outside a module?
A. exports.functionName = function(){};
B. module.exports = function(){};
C. global.functionName = function(){};
D. process.functionName = function(){};
Q.15 What is the output of
console.log(module.exports === exports);
A. true
B. false
C. undefined
D. null
Q.16 How do you import the ‘http’ module in Node.js?
A. const http = require(‘http’);
B. import http from ‘http’;
C. include http
D. http = require(‘http’);
Q.17 Which of the following is true about the ‘require’ function?
A. It blocks the event loop
B. It is asynchronous
C. It is non-blocking
D. It can load JSON files
Q.18 How can you export multiple functions from a module?
A. module.exports
B. exports
C. global
D. process
Q.19 Which object is used to manage modules in Node.js?
A. global
B. module
C. process
D. exports
Q.20 Which of the following is a core module in Node.js?
A. fs
B. express
C. mongoose
D. socket.io
Q.21 What is a core module in Node.js?
A. A user-defined module
B. A built-in module
C. A plugin
D. An external library
Q.22 Which method is used to import modules in Node.js?
A. require()
B. import()
C. include()
D. module()
Q.23 What is the main advantage of using Node.js for web applications?
A. High CPU usage
B. Low memory usage
C. Non-blocking I/O
D. Static typing
Q.24 Which protocol is primarily used in Node.js for communication?
A. FTP
B. HTTP
C. SMTP
D. SNMP
Q.25 Which of the following is a key feature of Node.js?
A. Synchronous execution
B. Single-threaded
C. Multi-threaded
D. Distributed
Q.26 What type of architecture does Node.js follow?
A. Blocking I/O
B. Non-blocking I/O
C. Procedural
D. Functional
Q.27 Which programming language is Node.js based on?
A. Python
B. Java
C. JavaScript
D. Ruby
Q.28 Node.js is designed to handle which type of operations efficiently?
A. Synchronous
B. Asynchronous
C. Parallel
D. Serial
Q.29 Which engine powers Node.js?
A. V8
B. SpiderMonkey
C. JavaScriptCore
D. Chakra
Q.30 What is Node.js primarily used for?
A. To create client-side interfaces
B. To act as a DBMS
C. To build server-side applications
D. To enhance CSS
Q.31 What should you check if an HTTP server in Node.js is not responding?
A. Server status
B. Network connection
C. Code syntax
D. HTTP version
Q.32 What is the output of the following code snippet?
const server = http.createServer((req, res) => { res.writeHead(200, {‘Content-Type’: ‘text/plain’}); res.end(‘OK’); });
A. Content-Type
B. 200 OK
C. plain text
D. OK
Q.33 How do you read the request headers in Node.js?
A. request.headers
B. request.getHeaders()
C. request.readHeaders()
D. request.httpHeaders()
Q.34 How do you write “Hello, World!” to the response in Node.js?
A. response.send(‘Hello, World!’)
B. response.write(‘Hello, World!’)
C. response.end(‘Hello, World!’)
D. response.print(‘Hello, World!’)
Q.35 How can you set the response HTTP status code in Node.js?
A. response.setStatus()
B. response.statusCode()
C. response.writeHead()
D. response.sendStatus()
Q.36 What does the response.end() method do in the HTTP module?
A. Sends headers
B. Ends the response
C. Sends data
D. Closes the server
Q.37 Which event is emitted when the HTTP server receives a request?
A. request
B. data
C. connection
D. receive
Q.38 Which method is used to create a server in Node.js using the HTTP module?
A. http.createServer()
B. http.initServer()
C. http.newServer()
D. http.startServer()
Q.39 What is the primary purpose of the HTTP module in Node.js?
A. To handle HTTP requests and responses
B. To handle file operations
C. To manage streams
D. To manage buffers
Q.40 How can you handle errors in a stream?
A. Using a try-catch block
B. Using the error event
C. Restarting the stream
D. Ignoring the errors
Q.41 What should you check if a readable stream is not emitting data?
A. Stream state
B. File permissions
C. Network connection
D. Buffer size
Q.42 What is the output of the following code:
const buf = Buffer.from(‘hello’); console.log(buf.toString(‘hex’));
A. 68656c6c6f
B. hello
C. 68656C6C6F
D. 5a5a5a5a5a
Q.43 How can you handle data events in a readable stream?
A. stream.on(‘data’, callback)
B. stream.read(callback)
C. stream.write(‘data’, callback)
D. stream.handle(‘data’, callback)
Q.44 How do you create a readable stream in Node.js?
A. new stream.Readable()
B. fs.createReadStream()
C. stream.createRead()
D. new stream.Read()
Q.45 What is the difference between Buffer.alloc and Buffer.allocUnsafe?
A. Buffer.alloc initializes the buffer with zeros
B. Buffer.allocUnsafe initializes the buffer with zeros
C. Buffer.alloc is deprecated
D. Buffer.allocUnsafe is deprecated
Q.46 How do you create a buffer of 10 bytes in Node.js?
A. Buffer.alloc(10)
B. Buffer.create(10)
C. new Buffer(10)
D. Buffer.init(10)
Q.47 What is a buffer in Node.js?
A. A temporary storage for data
B. A method to read files
C. A HTTP handler
D. A type of stream
Q.48 Which of the following is a type of stream in Node.js?
A. Readable
B. Writable
C. Duplex
D. All of these
Q.49 What is a stream in Node.js?
A. A way to handle I/O operations
B. A method for handling HTTP requests
C. A library for file manipulation
D. A type of database
Q.50 An application experiences high CPU usage and slow performance.
Which phase of the event loop might be causing this issue?
A. Poll phase
B. Timers phase
C. Close callbacks phase
D. Check phase
Q.51 How can you monitor the phases of the event loop in a Node.js application?
A. Using console.log()
B. Using a debugger
C. Using process.nextTick()
D. Using event listeners
Q.52 What is the output of the following code:
setTimeout(() => console.log(‘1’), 0); setImmediate(() => console.log(‘2’));
A. 1 2
B. 2 1
C. 1
D. 2
What is the output of the following code:
Q.53 console.log(‘1’); process.nextTick(() => console.log(‘2’)); console.log(‘3’);
A. 1 2 3
B. 1 3 2
C. 2 1 3
D. 3 2 1
Q.54 Which method is used to defer the execution of a function until the next iteration of the event loop?
A. setTimeout
B. setInterval
C. setImmediate
D. nextTick
Q.55 What is the primary benefit of Node.js’s event-driven architecture?
A. Improved security
B. Ease of use
C. Scalability
D. Compatibility with other languages
Q.56 Which phase of the event loop is responsible for executing callbacks from setImmediate()?
A. Poll phase
B. Check phase
C. Timers phase
D. Immediate phase
Q.57 What happens during the ‘poll’ phase of the event loop?
A. Execution of callbacks
B. Processing of events
C. Execution of expired timers
D. Execution of I/O callbacks
Q.58 Which phase of the event loop executes timers scheduled by setTimeout and setInterval?
A. Poll phase
B. Check phase
C. Timers phase
D. Close callbacks phase
Q.59 What is the role of the event loop in Node.js?
A. To execute synchronous code
B. To manage I/O operations
C. To enhance CSS
D. To handle database queries
Q.60 An application crashes with “Error: ENOENT, no such file or directory”.
What should you check?
A. Disk space
B. File path
C. Node.js version
D. Network connection
Q.61 How do you send a JSON response in Express.js?
A. res.sendJSON(data)
B. res.json(data)
C. res.send(data)
D. res.responseJSON(data)
Q.62 How do you parse JSON request bodies in Express.js?
A. app.use(express.json())
B. app.use(bodyParser.json())
C. app.use(jsonParser())
D. app.use(parseJSON())
Q.63 How do you define a route for a GET request in Express.js?
A. app.get(‘/path’, callback)
B. app.post(‘/path’, callback)
C. app.put(‘/path’, callback)
D. app.delete(‘/path’, callback)
Q.64 What is the primary advantage of using REST APIs?
A. Improved security
B. Statelessness
C. Stateful operations
D. Enhanced compatibility with HTML
Q.65 Which HTTP method is used to update a resource in a REST API?
A. GET
B. POST
C. PUT
D. DELETE
Q.66 Which status code indicates that a resource was successfully created?
A. 200
B. 201
C. 400
D. 404
Q.67 Which HTTP method is typically used to create a resource in a REST API?
A. GET
B. POST
C. PUT
D. DELETE
Q.68 What does REST stand for?
A. Representational State Transfer
B. Real-time State Transfer
C. Remote Service Technology
D. Reliable State Transfer
Q.69 How can you debug middleware execution in Express.js?
A. Using console.log()
B. Using a debugger
C. Checking middleware order
D. All of these
Q.70 What should you check if middleware is not being executed?
A. Middleware order
B. Middleware type
C. Middleware function name
D. Middleware parameters
Q.71 How do you define error-handling middleware in Express.js?
A. app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send(‘Something broke!’); })
B. app.use((err, req, res, next) => { console.error(err.stack); res.status(404).send(‘Not Found’); })
C. app.error((err, req, res, next) => { console.error(err.stack); res.status(500).send(‘Something broke!’); })
D. app.catch((err, req, res, next) => { console.error(err.stack); res.status(500).send(‘Something broke!’); })
Q.72 How can you handle JSON request bodies in Express.js?
A. app.use(express.json())
B. app.handle(express.json())
C. app.request(express.json())
D. app.json()
Q.73 How do you add a middleware function that logs request URLs?
A. app.use((req, res, next) => { console.log(req.url); next(); })
B. app.log((req, res, next) => { console.log(req.url); next(); })
C. app.request((req, res, next) => { console.log(req.url); next(); })
D. app.get((req, res, next) => { console.log(req.url); next(); })
Q.74 Which middleware function handles errors in Express.js?
A. app.error()
B. app.use()
C. app.catch()
D. app.handle()
Q.75 What is a common use case for middleware in Express.js?
A. Handling static files
B. Routing requests
C. Logging requests
D. Rendering views
Q.76 How do you define middleware in Express.js?
A. app.middleware()
B. app.use()
C. app.define()
D. app.create()
Q.77 What is middleware in Express.js?
A. Functions that execute before route handlers
B. Functions that execute after route handlers
C. Functions that handle file uploads
D. Functions that handle database connections
Q.78 What is the best practice for error handling in Express.js?
A. Using try-catch blocks
B. Using error-handling middleware
C. Restarting the server
D. Ignoring errors
Q.79 How can you debug an Express.js application?
A. Using a debugger
B. Using console.log()
C. Using nodemon
D. All of these
Q.80 What should you check if an Express.js route is not working?
A. Route path
B. Route method
C. Route handler
D. All of these
Q.81 How do you handle 404 errors in Express.js?
A. app.use((req, res, next) => { res.status(404).send(‘Not Found’); })
B. app.get((req, res, next) => { res.status(404).send(‘Not Found’); })
C. app.route((req, res, next) => { res.status(404).send(‘Not Found’); })
D. app.handle((req, res, next) => { res.status(404).send(‘Not Found’); })
Q.82 What is the output of the following code:
app.get(‘/’, (req, res) => { res.send(‘Hello, World!’); });
A. Error
B. Hello, World!
C. Empty response
D. HTML document
Q.83 How do you serve static files in Express.js?
A. app.use(express.static(‘public’))
B. app.serve(‘public’)
C. app.static(‘public’)
D. app.getStatic(‘public’)
Q.84 Which method is used to start a server in Express.js?
A. app.listen()
B. app.start()
C. app.run()
D. app.init()
Q.85 What is middleware in Express.js?
A. Functions that execute after route handlers
B. Functions that execute before route handlers
C. Functions that handle file uploads
D. Functions that handle database connections
Q.86 How can you handle HTTP POST requests in Express.js?
A. app.post()
B. app.get()
C. app.put()
D. app.delete()
Q.87 Which method is used to define a route in Express.js?
A. app.route()
B. app.router()
C. app.getRoute()
D. app.setRoute()
Q.88 How do you create a new Express application?
A. express()
B. express.createApp()
C. express.new()
D. express.init()
Q.89 What is Express.js primarily used for?
A. Building command-line tools
B. Creating web applications
C. Managing file systems
D. Handling HTTP requests and responses
Q.90 How can you debug an HTTP request error in Node.js?
A. Use console.log()
B. Use a debugger
C. Check the response headers
D. Check the HTTP method
Q.91 How do you handle uncaught exceptions in a Node.js application?
A. Using try-catch blocks
B. Using process.on(‘uncaughtException’, callback)
C. Using a promise
D. Using setTimeout
Q.92 How do you propagate an error in a callback function in Node.js?
A. return error
B. throw error
C. next(error)
D. process.exit(1)
Q.93 How do you handle errors in an Express.js middleware function?
A. Using try-catch blocks
B. Using if-else statements
C. Using error-handling middleware
D. Using callbacks
Q.94 How do you define a custom error in Node.js?
A. throw new Error(‘message’)
B. console.error(‘message’)
C. process.exit(1)
D. return new Error(‘message’)
Q.95 What is the purpose of a try-catch block in JavaScript?
A. To handle asynchronous operations
B. To catch and handle exceptions
C. To manage HTTP requests
D. To handle database queries
Q.96 Which module is commonly used for logging errors in a Node.js application?
A. fs
B. path
C. winston
D. http
Q.97 What is the primary purpose of error handling in Node.js?
A. To manage database connections
B. To handle HTTP requests
C. To catch and manage runtime errors
D. To improve performance
Q.98 How can you debug issues with Passport.js authentication?
A. Check strategy configuration
B. Check middleware order
C. Check session settings
D. Check callback URL
Q.99 What should you check if JWT authentication fails in your application?
A. Token expiry
B. Token signature
C. User permissions
D. Token payload
Q.100 How do you use Passport.js to authenticate users with Google OAuth?
A. passport.use(new GoogleStrategy(…));
B. passport.use(new OAuthStrategy(…));
C. passport.use(new GoogleAuth(…));
D. passport.use(new AuthStrategy(…));
Q.101 How do you protect a route using JWT in Express.js?
A. app.use(jwtAuth);
B. app.get(‘/protected’, jwtAuth, (req, res) => {…});
C. app.use(jwtAuth());
D. app.get(‘/protected’, (req, res) => { jwtAuth(); … });
Q.102 How do you initialize Passport.js in an Express.js application?
A. app.use(passport.init());
B. app.use(passport.start());
C. app.use(passport.initialize());
D. app.use(passport.begin());
Q.103 What is the purpose of the Passport.js library in a Node.js application?
A. To manage database connections
B. To handle routing
C. To authenticate requests
D. To parse JSON bodies
Q.104 What is the main advantage of using OAuth for authentication?
A. Simplicity
B. Improved security
C. Speed
D. Ease of use
Q.105 Which of the following is a common strategy for implementing authentication in Express.js applications?
A. OAuth
B. JWT
C. Session-based
D. Cookie-based
Q.106 What is the primary purpose of JWT (JSON Web Token) in authentication?
A. To store session data
B. To encrypt passwords
C. To transmit information securely
D. To manage user roles
Q.107 How can you debug database queries in Mongoose?
A. Using a debugger
B. Using mongoose.set(‘debug’, true)
C. Checking model definitions
D. Checking schema definitions
Q.108 What should you check if a MongoDB connection fails in Mongoose?
A. Connection string
B. Model definition
C. Schema validation
D. Middleware
Q.109 How do you update an existing document in Mongoose?
A. Model.update(query, update)
B. Model.updateOne(query, update)
C. Model.modify(query, update)
D. Model.change(query, update)
Q.110 How do you save a new document to a MongoDB collection using Mongoose?
A. const doc = new Model(data); doc.save();
B. Model.insert(data);
C. Model.create(data);
D. const doc = new Model(data); doc.insert();
Q111 How do you define a schema in Mongoose?
A. new mongoose.Schema()
B. mongoose.createSchema()
C. mongoose.initSchema()
D. new Schema()
Q.112 What is the purpose of model validation in Mongoose?
A. To validate JavaScript code
B. To ensure data integrity
C. To check database connection
D. To manage middleware
Q.113 What is a schema in Mongoose?
A. A function to run database queries
B. A middleware function
C. A blueprint for defining the structure of a document
D. A method for connecting to the database
Q.114 Which method is used to save a document to a MongoDB collection in Mongoose?
A. save
B. insert
C. create
D. update
Q.115 What does the mongoose.connect() method do?
A. Closes the database connection
B. Opens a new database connection
C. Runs a database query
D. Initializes the Mongoose library
Q.116 Which module is commonly used for MongoDB integration in Node.js?
A. mongoose
B. mysql
C. sequelize
D. pg
Q.117 What is a common cause of CORS errors in REST APIs?
A. Incorrect URL
B. Invalid JSON
C. Cross-origin requests
D. Server overload
Q.118 How can you debug a REST API request in Node.js?
A. Using console.log()
B. Using a debugger
C. Using Postman
D. Checking network tab in browser
Q.119 What should you check if a REST API is not returning the expected data?
A. API endpoint
B. HTTP method
C. Request payload
D. Response format
Q.120 How do you handle errors in a REST API using Express.js?
A. app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); })
B. app.use((req, res, next) => { res.status(500).json({ error: ‘Server error’ }); })
C. app.use((req, res, next) => { res.json({ error: ‘Server error’ }); })
D. app.use((err, req, res, next) => { res.send({ error: ‘Server error’ }); })
Q.121 What is the best practice for handling environment variables in a Node.js application?
A. Hardcoding them in the application
B. Storing them in a .env file
C. Passing them as command-line arguments
D. Storing them in a database
Q.122 How can you monitor the performance of a deployed Node.js application?
A. Using console.log()
B. Using monitoring tools like New Relic or Datadog
C. Using a debugger
D. Using npm scripts
Q.123 What should you check if a deployed Node.js application is not responding?
A. Application logs
B. Database connection
C. Network configuration
D. All of these
Q.124 How do you create a Dockerfile for a Node.js application?
A. FROM node:latest
B. COPY package*.json ./
C. RUN npm install
D. CMD [“node”, “app.js”]
Q.125 How do you start a Node.js application with PM2?
A. pm2 init app.js
B. pm2 start app.js
C. pm2 run app.js
D. pm2 serve app.js
Q.126 What is a key benefit of using a reverse proxy like Nginx with a Node.js application?
A. To handle static files
B. To balance load and improve scalability
C. To manage database connections
D. To write application code
Q.127 What is the purpose of using a process manager like PM2?
A. To write application code
B. To handle database operations
C. To manage application processes
D. To create user interfaces
Q.128 Which of the following is a common method for deploying Node.js applications?
A. FTP
B. SSH
C. Docker
D. SMTP
Q.129 What is the primary purpose of deploying a Node.js application?
A. To run the application in a production environment
B. To improve development speed
C. To manage database connections
D. To handle HTTP requests
Q.130 What is the best practice for writing test cases in Node.js?
A. Writing long and complex tests
B. Testing multiple functionalities in one test
C. Writing small and focused tests
D. Ignoring edge cases
Q.131 How can you debug a failing test case in Node.js?
A. Using console.log()
B. Using a debugger
C. Using a testing framework
D. Using process.exit()
Q.132 What should you do if a test case fails unexpectedly?
A. Check the test logic
B. Check the implementation code
C. Check the test environment
D. All of these
Q.133 How do you mock a function using Sinon?
A. sinon.mock(functionName)
B. sinon.stub(object, ‘method’)
C. sinon.spy(functionName)
D. sinon.fake(functionName)
Q.134 How do you write a simple test case using Mocha?
A. describe(‘test’, function() { it(‘should pass’, function() { assert(true); }); });
B. test(‘should pass’, function() { assert(true); });
C. mocha(‘test’, function() { it(‘should pass’, function() { assert(true); }); });
D. describe(‘test’, function() { test(‘should pass’, function() { assert(true); }); });
Q.135 What is the advantage of using assertion libraries in testing?
A. To improve performance
B. To provide descriptive error messages
C. To manage HTTP requests
D. To handle file operations
Q.136 What is the purpose of a test runner in Node.js?
A. To execute test cases
B. To handle HTTP requests
C. To manage database connections
D. To debug code
Q.137 Which testing framework is commonly used in Node.js applications?
A. React
B. Express
C. Mocha
D. Nginx
Q.138 What is the primary purpose of testing in Node.js applications?
A. To improve performance
B. To find and fix bugs
C. To manage database connections
D. To handle HTTP requests
Q.139 What is the best practice for logging in a Node.js application?
A. Using console.log()
B. Using a logging library
C. Using error-handling middleware
D. Using process.stdout
Q.140 How can you debug memory leaks in a Node.js application?
A. Using a debugger
B. Using heap snapshots
C. Using CPU profiles
D. Using process.exit()
Q.141 What should you check if a Node.js application is running slowly?
A. Memory usage
B. CPU usage
C. I/O operations
D. All of these
Q.142 How do you capture a CPU profile in Node.js?
A. node –prof app.js
B. node –inspect app.js
C. node –cpu app.js
D. node –profile app.js
Q.143 How do you start the Node.js inspector?
A. node inspect app.js
B. node debug app.js
C. node start app.js
D. node profiler app.js
Q.144 Which tool can be used to visualize the performance profile of a Node.js application?
A. npm
B. node-gyp
C. chrome-devtools
D. express
Q.145 What is the V8 profiler used for in Node.js?
A. To profile JavaScript execution
B. To debug HTTP requests
C. To manage file operations
D. To handle database connections
Q.146 Which built-in Node.js module is used for debugging?
A. fs
B. util
C. path
D. inspector
Q.147 What is the primary purpose of profiling in Node.js?
A. To improve security
B. To analyze performance
C. To handle HTTP requests
D. To manage database connections
Q.148 What is the best practice for handling promise rejections in Node.js?
A. Using .catch() method
B. Using try-catch block
C. Using .then() method
D. Ignoring rejections
Q.149 How can you debug an error that occurs in a Node.js application?
A. Using console.log()
B. Using a debugger
C. Using logging libraries
D. Using all of these methods
Q.150 What should you check if an Express.js application is not handling errors properly?
A. Middleware order
B. Route definitions
C. Database connections
D. Server configuration