0% found this document useful (0 votes)
2 views

What Are Callbacks in Node

The document explains key concepts in Node.js, including callbacks for handling asynchronous operations, Express.js for creating web servers, and Streams for efficient data processing. It also covers error handling strategies, async/await syntax for cleaner asynchronous code, and connecting to a MongoDB database using Mongoose. Additionally, it provides examples of creating a simple HTTP server and reading/writing files using the fs module.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

What Are Callbacks in Node

The document explains key concepts in Node.js, including callbacks for handling asynchronous operations, Express.js for creating web servers, and Streams for efficient data processing. It also covers error handling strategies, async/await syntax for cleaner asynchronous code, and connecting to a MongoDB database using Mongoose. Additionally, it provides examples of creating a simple HTTP server and reading/writing files using the fs module.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

What are callbacks in Node.js?

How do
you handle asynchronous operations?
Answer: Callbacks are functions passed as arguments to other
functions, to be executed once an asynchronous operation
completes. They are a core feature in Node.js for handling
asynchronous tasks. Example:
// Example of asynchronous file reading
using callbacks
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err,
data) => {
if (err) throw err;
console.log(data);
});

// Example demonstra0ng setImmediate() and setTimeout()


setImmediate(() => { console.log('This will execute
immediately'); });
setTimeout(() => { console.log('This will execute aCer 2000
milliseconds'); }, 2000);

What is Express.js? How do you create


a basic server using Express?
Answer: Express.js is a web application framework for
Node.js. It simplifies the process of building web servers and
APIs. Here's a basic example of creating a server using
Express:

// Example: Creating a basic server with


Express.js
const express = require('express');
const app = express();
const port = 3000;

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


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

app.listen(port, () => {
console.log(`Server running at
http://localhost:${port}`);
});

What are Streams in Node.js? How are


they useful?
Answer: Streams are objects that allow you to read data from
a source or write data to a destination continuously. They are
useful for handling large datasets or real-time data processing
efficiently. Example:

// Example: Using Streams in Node.js


const fs = require('fs');
const readStream =
fs.createReadStream('input.txt', 'utf8');
const writeStream =
fs.createWriteStream('output.txt');

readStream.pipe(writeStream);
console.log('Data copied successfully
using streams.');

6. How do you use async/await in


Node.js?
Answer: async functions in Node.js allow you to write
asynchronous code that looks synchronous. await is used to
wait for a Promise to resolve or reject inside an async
function.
Example using async/await:

async function readFileAsync() {


try {
const data = await
fs.readFile('file.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
readFileAsync();

8. How do you handle middleware in


Express.js?
Answer: Middleware functions in Express.js have access to
the request (req) and response (res) objects. They can
execute code, modify req and res objects, and end the
request-response cycle. Use app.use() to apply
middleware globally or to specific routes.
Example:

// Example middleware function


const logMiddleware = (req, res, next) =>
{
console.log('Request received:',
req.method, req.url);
next(); // Call next middleware
function or route handler
};

app.use(logMiddleware);

Handling errors in Node.js applications is crucial


for maintaining stability, providing meaningful
feedback to users, and ensuring security. Here are
several strategies and best practices for handling
errors in Node.js:

1.

Use Try-Catch Blocks: For synchronous code, use


try-catch blocks to catch and handle errors.
try {
// Code that might throw an error
} catch (error) {
// Handle the error
console.error('An error occurred:',
error);
}

1. Promise Error Handling: For asynchronous


code using Promises, chain a .catch() block
to handle rejections.

const myPromise = new Promise((resolve,


reject) => {
setTimeout(() => {
resolve('Success!');
}, 1000);
});
myPromise.then(result => {
console.log(result);
}).catch(error => {
console.error

1. Async/Await Error Handling: For


asynchronous code using async/await, wrap
the awaited code in a try-catch block.

What is async/await and how does it


work in Node.js?
• Answer: async/await is syntax built on Promises
that allows you to write asynchronous code that looks
synchronous. An async function returns a Promise, and
await pauses the execution of the async function until
the Promise is resolved or rejected.

async function fetchData() {


try {
const response = await
fetch('https://api.example.com/data');
const data = await
response.json();
console.log(data);
} catch (error) {
console.error('Error fetching
data:', error);
}
}

fetchData();

1. Express.js Error Handling: In Express.js


applications, use middleware to catch and
handle errors.

app.use((err, req, res, next) => {


console.error('An error occurred:',
err);
res.status(500).send('Something
broke!');
});

How do you connect to a MongoDB


database using Mongoose in Node.js?
• Answer:

const mongoose = require('mongoose');


mongoose.connect('mongodb://localhost:270
17/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
});

const db = mongoose.connection;
db.on('error',
console.error.bind(console, 'connection
error:'));
db.once('open', () => {
console.log('Connected to the
database');
});

Write a simple HTTP server using the


http module.
• Answer:

const http = require('http');

const server = http.createServer((req,


res) => {
res.statusCode = 200;
res.setHeader('Content-Type',
'text/plain');
res.end('Hello, World!\n');
});
server.listen(3000, () => {
console.log('Server running at
http://localhost:3000/');
});

Demonstrate how to read and write files


using the fs module.
• Answer:

const fs = require('fs');

// Reading a file
fs.readFile('example.txt', 'utf8',
(err, data) => {
if (err) {
console.error('Error reading
file:', err);
return;
}
console.log('File content:', data);
});

// Writing to a file
fs.writeFile('example.txt', 'Hello,
Node.js!', (err) => {
if (err) {
console.error('Error writing
file:', err);
return;
}
console.log('File written
successfully');
});

You might also like