1. What is Node.
js, and how does it differ from traditional server-side platforms like Apache or
PHP?
[Link] is an open-source, cross-platform JavaScript runtime built on Chrome's V8 engine. It
allows developers to run JavaScript on the server side.
Differences:
[Link] uses JavaScript, while traditional platforms like PHP use their own languages.
[Link] is non-blocking and event-driven, making it faster and suitable for real-time
applications.
Traditional platforms like Apache with PHP are generally synchronous and multi-threaded.
2. What is the purpose of the V8 engine in [Link]?
The V8 engine, developed by Google, compiles JavaScript directly into machine code.
In [Link], it ensures fast execution of JavaScript on the server, powering Node’s
performance and efficiency.
3. Explain the single-threaded, event-driven architecture of [Link].
[Link] uses a single thread to handle all requests, relying on an event loop to manage
operations.
The event loop offloads long operations (like file I/O or HTTP requests) to the system.
Once done, the callback is queued and executed.
This enables concurrency without multi-threading, making [Link] lightweight and fast.
4. Why is [Link] considered non-blocking?
[Link] is non-blocking because it doesn’t wait for operations like file reading or database
queries to finish.
Instead, it continues running other code and executes a callback once the task is complete.
5. What is npm, and how is it used in [Link]?
npm (Node Package Manager) is the default package manager for [Link].
It’s used to:
Install packages (libraries/tools)
Manage dependencies
Run scripts
6. What is a module in [Link]? How do you export and import modules?
A module is a reusable block of code. [Link] has built-in, third-party, and custom modules.
// [Link]
function add(a, b) { return a + b; }
[Link] = { add };
const math = require('./math');
[Link]([Link](2, 3));
7. What is the difference between require() and import in [Link]?
Feature require() import
Syntax CommonJS ES6 Modules
Usage Default in older [Link] Needs "type": "module" in [Link]
Sync/Async Synchronous Asynchronous
Example const fs = require('fs') import fs from 'fs'
8. How can you create a custom module in [Link]?
1. Create a file [Link]:
function hello(name) {
return `Hello, ${name}`;
}
[Link] = hello;
const greet = require('./greet');
[Link](greet('Sam'));
9. What is the role of the [Link] file in a [Link] project?
[Link]:
Stores project metadata (name, version, scripts)
Lists dependencies
Allows easy sharing and installation
10. How do you install a package globally and locally using npm?
Local installation (default):
npm install lodash
Global installation (for CLI tools):
npm install -g nodemon
11. What is the difference between asynchronous and synchronous programming in [Link]?
Feature Synchronous Asynchronous
Blocking Yes No
Execution One-by-one Non-blocking with callbacks/promises
Example
// Sync
const data = [Link]('[Link]');
// Async
[Link]('[Link]', (err, data) => {
if (err) throw err;
});
12. How do you create an HTTP server in [Link]?
const http = require('http');
const server = [Link]((req, res) => {
[Link]('Hello World');
[Link]();
});
[Link](3000, () => {
[Link]('Server running on port 3000');
});
13. What is the difference between [Link]() and using frameworks like [Link]?
Feature [Link]() [Link]
Low-level Yes No
Routing Manual Built-in
Middleware Manual Built-in
Use case Simple servers Scalable web apps/API
14. How do you handle GET and POST requests in [Link]?
Using http module:
const http = require('http');
const querystring = require('querystring');
[Link]((req, res) => {
if ([Link] === 'GET') {
[Link]('GET Request');
} else if ([Link] === 'POST') {
let body = '';
[Link]('data', chunk => body += chunk);
[Link]('end', () => {
const data = [Link](body);
[Link](`POST Data: ${[Link](data)}`);
});
}
}).listen(3000);
Using Express (simpler):
const express = require('express');
const app = express();
[Link]([Link]({ extended: true }));
[Link]([Link]());
[Link]('/', (req, res) => [Link]('GET Request'));
[Link]('/', (req, res) => [Link]([Link]));
[Link](3000);
1. What is Middleware in [Link] ([Link])?
Middleware in [Link] is a function that has access to the request (req), response (res), and
the next middleware function (next) in the application's request-response cycle.
It is used to:
Execute any code
Modify the request or response objects
End the request-response cycle
Call the next middleware in the stack
Syntax of Middleware Function:
function (req, res, next) {
// Code to execute
next(); // Passes control to the next middleware
}
2. How to Create Custom Middleware in [Link]?
You can define your own middleware by writing a function and using [Link]() or attaching it to
specific routes.
const express = require('express');
const app = express();
// Custom middleware function
function logRequest(req, res, next) {
[Link](`${[Link]} ${[Link]}`);
next(); // Move to the next middleware
}
// Use the middleware
[Link](logRequest);
[Link]('/', (req, res) => {
[Link]('Home Page');
});
[Link](3000, () => {
[Link]('Server is running on port 3000');
});
3. How Middleware is Executed in Order in [Link]?
Express executes middleware in the order it is defined in the code.
The request flows through the middleware stack until a response is sent or the stack ends.
If any middleware does not call next(), the request is stopped there.
Middleware can be global (using [Link]()) or route-specific.
Execution Flow Example:
[Link](middleware1);
[Link](middleware2);
[Link]('/', (req, res) => {
[Link]('Hello World');
});
1. How do you read and write files using the fs module in [Link]?
To read and write files in [Link], the fs (File System) module is used. It provides both
asynchronous and synchronous methods. Reading allows you to access file content, while writing
lets you create or modify files. Asynchronous methods are preferred for non-blocking operations.
Reading a File (Asynchronous):
const fs = require('fs');
[Link]('[Link]', 'utf8', (err, data) => {
if (err) throw err;
[Link](data);
});
Writing to a File (Asynchronous):
[Link]('[Link]', 'Hello, World!', (err) => {
if (err) throw err;
[Link]('File written successfully!');
});
2. What is the difference between [Link]() and [Link]()?
[Link]() is asynchronous, meaning it does not block other operations and uses a
callback function.
[Link]() is synchronous, meaning it blocks further execution until the file is
completely read.
Asynchronous functions are more efficient for large-scale applications, while synchronous
methods are suitable for small scripts or when blocking is acceptable.
3. How can you check if a file or directory exists in [Link]?
You can check the existence of a file or directory using built-in methods provided by the fs module.
This can be done either synchronously or asynchronously. These methods help you determine
whether a specific path or file is accessible or not before performing file operations.
Using [Link]() (Synchronous):
const fs = require('fs');
if ([Link]('[Link]')) {
[Link]('File exists');
} else {
[Link]('File does not exist');
}
Using [Link]() (Asynchronous):
[Link]('[Link]', [Link].F_OK, (err) => {
[Link](err ? 'File does not exist' : 'File exists');
});
4. How do you handle file operations in an asynchronous manner?
Asynchronous file operations are handled using callback functions or by utilizing Promises and
async/await. This approach allows other processes to continue running without waiting for the file
operation to complete, making the application faster and more responsive.
Using Promises with [Link]:
const fs = require('fs').promises;
async function readFileAsync() {
try {
const data = await [Link]('[Link]', 'utf8');
[Link](data);
} catch (err) {
[Link](err);
}
}
readFileAsync();
1. How do you connect to a SQL or Oracle database from a [Link] application?
To connect a [Link] application to a SQL (like MySQL, PostgreSQL) or Oracle database, you
need:
The respective database driver or library installed via npm (like mysql2 for MySQL,
oracledb for Oracle).
Proper connection configuration, which includes:
o Hostname or IP address
o Port number
o Database name
o Username and password
The process typically involves:
Installing the library using npm.
Importing the library into your [Link] app.
Creating a connection or a connection pool.
Executing queries using functions provided by the library.
Handling results and errors.
2. What is the purpose of the mysql2 library in [Link]?
The mysql2 library is a modern and faster MySQL client for [Link]. Its key purposes include:
Providing a better performance alternative to the original mysql library.
Supporting Promises and async/await, making asynchronous code cleaner and more
manageable.
Allowing prepared statements to prevent SQL injection.
Supporting connection pooling, making database access more efficient in high-load
applications.
It is widely used for interacting with MySQL databases in production-grade [Link] applications.
[Link] how you would perform basic CRUD operations (Create, Read, Update, Delete) using
MySQL and [Link].
1. Create (Insert Data)
To add data to a MySQL database from a [Link] application:
Establish a connection to the MySQL database using a library like mysql2.
Use an INSERT INTO SQL query with parameters or values.
Execute the query and handle the result to confirm data insertion or catch any errors.
2. Read (Retrieve Data)
To fetch data from the database:
Use a SELECT SQL query to retrieve records from a specific table.
The data can be filtered using conditions (e.g., WHERE clause).
The result is returned as rows, which can be processed or displayed in the app.
3. Update (Modify Existing Data)
To modify records in a table:
Use an UPDATE SQL query with a SET clause to define new values.
Use a WHERE clause to specify which records should be updated.
After execution, check how many rows were affected to confirm the update.
4. Delete (Remove Data)
To delete records:
Use a DELETE FROM SQL query along with a WHERE clause to specify which records
should be removed.
Avoid deleting all data unless that’s intentional (omit the WHERE clause carefully).
Handle the response to verify how many rows were deleted.