Basic Node.
js Questions
What is Node.js?
Node.js is an open-source, cross-platform runtime environment built on Chrome’s V8 JavaScript
engine. It allows developers to execute JavaScript code outside of a web browser, primarily on the
server side. Node.js is especially suited for building fast and scalable network applications because
of its non-blocking, event-driven architecture.
How is Node.js different from JavaScript in the browser?
In the browser, JavaScript interacts with the DOM, handles events, and manages UI logic. Node.js,
however, does not have a DOM or browser-specific APIs. Instead, it provides system-level modules
like 'fs' for file handling, 'http' for creating servers, and more, making it suitable for backend
development.
What are the main features of Node.js?
- Asynchronous and Event-driven: Non-blocking I/O ensures scalability. - Single-threaded: Efficient
handling of multiple connections. - Fast Execution: Powered by Google’s V8 engine. - NPM
Ecosystem: Access to thousands of reusable packages. - Cross-platform support.
What is npm?
npm (Node Package Manager) is the default package manager for Node.js. It is used to install,
manage, and share third-party libraries and tools. It also helps manage project dependencies via
'package.json'.
What is the difference between CommonJS (require) and ES6 Modules
(import)?
CommonJS is the older module system in Node.js where modules are imported using 'require()'.
ES6 Modules use the 'import' and 'export' syntax and are standardized in modern JavaScript.
CommonJS loads modules synchronously, while ES6 modules can be loaded asynchronously.
Core Concepts
What is the event loop in Node.js?
The event loop is the mechanism that allows Node.js to perform non-blocking operations despite
being single-threaded. It continuously checks the call stack and callback queue, processing events
and executing asynchronous callbacks.
Explain the difference between synchronous and asynchronous code.
Synchronous code executes line by line, blocking further execution until the current task completes.
Asynchronous code, on the other hand, allows tasks to run in the background without blocking, so
multiple operations can be handled concurrently.
What are callbacks in Node.js?
Callbacks are functions passed as arguments to other functions, executed once the task is
complete. For example, 'fs.readFile("file.txt", (err, data) => { ... })'. While powerful, excessive
callbacks can lead to 'callback hell'.
What are Promises and async/await?
Promises represent a value that may be available now, later, or never. They help manage
asynchronous operations. Async/await is syntactic sugar over promises, making asynchronous
code look synchronous and more readable.
What is the difference between process.nextTick() and setImmediate()?
'process.nextTick()' executes callbacks after the current operation, before the event loop continues.
'setImmediate()' executes callbacks on the next iteration of the event loop. Thus, 'nextTick' has
higher priority than 'setImmediate'.
Modules & File System
How do you create and use modules in Node.js?
You can create a module by exporting functionality using 'module.exports'. Then import it into
another file using 'require()'. Example: // math.js module.exports.add = (a, b) => a + b; // app.js
const math = require('./math'); console.log(math.add(2, 3));
What is the difference between require() and import?
'require()' is used in CommonJS modules and loads modules synchronously. 'import' is part of ES6
Modules, supporting asynchronous loading and static analysis.
How do you read/write files in Node.js?
The 'fs' module provides methods for file operations. Example: fs.readFile('file.txt', 'utf8', (err, data)
=> { console.log(data); }); fs.writeFile('output.txt', 'Hello World', err => { if (err) throw err; });
What are streams in Node.js?
Streams are objects that enable reading or writing data continuously. Types include: - Readable
(e.g., fs.createReadStream) - Writable (e.g., fs.createWriteStream) - Duplex (both readable and
writable) - Transform (modify data as it passes).
HTTP & Express
How do you create a simple server in Node.js?
Using the built-in 'http' module: const http = require('http'); const server = http.createServer((req,
res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World'); });
server.listen(3000, () => console.log('Server running on port 3000'));
What is Express.js and why is it used with Node.js?
Express.js is a lightweight web framework for Node.js. It simplifies handling HTTP requests, routing,
middleware, and APIs. It is the most widely used framework for building RESTful services and web
applications.
What are middleware functions in Express.js?
Middleware are functions that process requests before sending a response. They can log requests,
authenticate users, handle errors, etc. Each middleware function receives (req, res, next).
How do you handle routing in Express?
Routing defines endpoints for handling requests. Example: app.get('/users', (req, res) =>
res.send('User list')); app.post('/users', (req, res) => res.send('User created'));
How do you send JSON response in Node.js?
In Express.js: res.json({ message: 'Hello World' }); In raw Node.js: res.writeHead(200,
{'Content-Type': 'application/json'}); res.end(JSON.stringify({ message: 'Hello World' }));
Error Handling
How do you handle errors in Node.js?
Node.js uses error-first callbacks, try/catch for synchronous code, and Express error-handling
middleware. Example: app.use((err, req, res, next) => { res.status(500).send(err.message); });
Difference between operational errors and programmer errors?
- Operational Errors: Expected runtime problems (e.g., file not found, DB connection error). -
Programmer Errors: Bugs in code (e.g., null dereference, wrong logic). Operational errors should be
handled gracefully; programmer errors often require fixing code.
Database Integration
How do you connect Node.js with a database (e.g., MongoDB, MySQL)?
Node.js connects to databases via drivers or ORMs. Example (MongoDB): const mongoose =
require('mongoose'); mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true
});
What are ORMs and ODMs? Give examples.
ORM (Object-Relational Mapping) is used with SQL databases (e.g., Sequelize, Prisma). ODM
(Object-Document Mapping) is used with NoSQL databases (e.g., Mongoose for MongoDB).
Security & Best Practices
What are some common security issues in Node.js applications?
- SQL Injection - Cross-Site Scripting (XSS) - Cross-Site Request Forgery (CSRF) - Insecure JWT
handling - Improper error handling revealing sensitive data.
How do you store environment variables in Node.js?
Sensitive data like API keys should be stored in a .env file and accessed using the 'dotenv'
package: require('dotenv').config(); console.log(process.env.DB_PASSWORD);
General & Practical
Why is Node.js good for real-time applications?
Because it is event-driven and uses WebSockets for persistent connections, Node.js is ideal for
chat applications, live notifications, and collaborative tools.
What is clustering in Node.js?
Clustering allows Node.js to use multiple worker processes to handle requests, taking advantage of
multi-core CPUs. Example: const cluster = require('cluster');
What is the difference between spawn and fork in Node.js?
'spawn' launches a new process with a given command. 'fork' is a special case of spawn that
creates a new Node.js process and establishes communication channels.
How do you debug a Node.js application?
Debugging can be done using: - console.log statements - Node.js Inspector: node --inspect app.js -
Debugging tools like Chrome DevTools or VSCode debugger.
What is the difference between == and === in JavaScript?
'==' checks for equality with type coercion (e.g., '5' == 5 is true). '===' checks for strict equality
without type coercion (e.g., '5' === 5 is false).