[go: up one dir, main page]

0% found this document useful (0 votes)
12 views10 pages

Webdev 8

Node.js is an open-source JavaScript runtime that differs from traditional server-side platforms by being non-blocking and event-driven, which enhances performance for real-time applications. It utilizes the V8 engine for fast execution and employs a single-threaded architecture to manage requests efficiently. The document also covers npm, module handling, middleware in Express.js, file operations, and database connectivity, providing a comprehensive overview of Node.js capabilities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views10 pages

Webdev 8

Node.js is an open-source JavaScript runtime that differs from traditional server-side platforms by being non-blocking and event-driven, which enhances performance for real-time applications. It utilizes the V8 engine for fast execution and employs a single-threaded architecture to manage requests efficiently. The document also covers npm, module handling, middleware in Express.js, file operations, and database connectivity, providing a comprehensive overview of Node.js capabilities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

1. What is Node.

js, and how does it differ from traditional server-side platforms like Apache or
PHP?
Node.js 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:
 Node.js uses JavaScript, while traditional platforms like PHP use their own languages.
 Node.js 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 Node.js?
 The V8 engine, developed by Google, compiles JavaScript directly into machine code.
In Node.js, it ensures fast execution of JavaScript on the server, powering Node’s
performance and efficiency.
3. Explain the single-threaded, event-driven architecture of Node.js.
Node.js 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 Node.js lightweight and fast.
4. Why is Node.js considered non-blocking?
 Node.js 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 Node.js?
npm (Node Package Manager) is the default package manager for Node.js.
It’s used to:
 Install packages (libraries/tools)
 Manage dependencies
 Run scripts
6. What is a module in Node.js? How do you export and import modules?
 A module is a reusable block of code. Node.js has built-in, third-party, and custom modules.
// math.js
function add(a, b) { return a + b; }
module.exports = { add };
const math = require('./math');
console.log(math.add(2, 3));

7. What is the difference between require() and import in Node.js?

Feature require() import

Syntax CommonJS ES6 Modules

Usage Default in older Node.js Needs "type": "module" in package.json

Sync/Async Synchronous Asynchronous

Example const fs = require('fs') import fs from 'fs'

8. How can you create a custom module in Node.js?


1. Create a file greet.js:
function hello(name) {
return `Hello, ${name}`;
}
module.exports = hello;
const greet = require('./greet');
console.log(greet('Sam'));

9. What is the role of the package.json file in a Node.js project?


package.json:
 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 Node.js?

Feature Synchronous Asynchronous

Blocking Yes No

Execution One-by-one Non-blocking with callbacks/promises

Example

// Sync
const data = fs.readFileSync('file.txt');
// Async
fs.readFile('file.txt', (err, data) => {
if (err) throw err;
});
12. How do you create an HTTP server in Node.js?
const http = require('http');

const server = http.createServer((req, res) => {


res.write('Hello World');
res.end();
});

server.listen(3000, () => {
console.log('Server running on port 3000');
});
13. What is the difference between http.createServer() and using frameworks like Express.js?

Feature http.createServer() Express.js

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 Node.js?


Using http module:
const http = require('http');
const querystring = require('querystring');

http.createServer((req, res) => {


if (req.method === 'GET') {
res.end('GET Request');
} else if (req.method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
const data = querystring.parse(body);
res.end(`POST Data: ${JSON.stringify(data)}`);
});
}
}).listen(3000);

Using Express (simpler):


const express = require('express');
const app = express();

app.use(express.urlencoded({ extended: true }));


app.use(express.json());

app.get('/', (req, res) => res.send('GET Request'));


app.post('/', (req, res) => res.send(req.body));

app.listen(3000);

1. What is Middleware in Node.js (Express.js)?


Middleware in Express.js 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 Express.js?


You can define your own middleware by writing a function and using app.use() or attaching it to
specific routes.

const express = require('express');


const app = express();

// Custom middleware function


function logRequest(req, res, next) {
console.log(`${req.method} ${req.url}`);
next(); // Move to the next middleware
}

// Use the middleware


app.use(logRequest);

app.get('/', (req, res) => {


res.send('Home Page');
});

app.listen(3000, () => {
console.log('Server is running on port 3000');
});

3. How Middleware is Executed in Order in Express.js?


 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 app.use()) or route-specific.

Execution Flow Example:


app.use(middleware1);
app.use(middleware2);

app.get('/', (req, res) => {


res.send('Hello World');
});

1. How do you read and write files using the fs module in Node.js?
To read and write files in Node.js, 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');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});

Writing to a File (Asynchronous):

fs.writeFile('example.txt', 'Hello, World!', (err) => {


if (err) throw err;
console.log('File written successfully!');
});

2. What is the difference between fs.readFile() and fs.readFileSync()?


 fs.readFile() is asynchronous, meaning it does not block other operations and uses a
callback function.
 fs.readFileSync() 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 Node.js?


 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 fs.existsSync() (Synchronous):

const fs = require('fs');

if (fs.existsSync('example.txt')) {
console.log('File exists');
} else {
console.log('File does not exist');
}
Using fs.access() (Asynchronous):
fs.access('example.txt', fs.constants.F_OK, (err) => {
console.log(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 fs.promises:

const fs = require('fs').promises;

async function readFileAsync() {


try {
const data = await fs.readFile('example.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
readFileAsync();
1. How do you connect to a SQL or Oracle database from a Node.js application?
To connect a Node.js 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 Node.js 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 Node.js?
The mysql2 library is a modern and faster MySQL client for Node.js. 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 Node.js applications.
3.Explain how you would perform basic CRUD operations (Create, Read, Update, Delete) using
MySQL and Node.js.
1. Create (Insert Data)
To add data to a MySQL database from a Node.js 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.

You might also like