What Are Callbacks in Node
What Are Callbacks in Node
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);
});
app.listen(port, () => {
console.log(`Server running at
http://localhost:${port}`);
});
readStream.pipe(writeStream);
console.log('Data copied successfully
using streams.');
app.use(logMiddleware);
1.
fetchData();
const db = mongoose.connection;
db.on('error',
console.error.bind(console, 'connection
error:'));
db.once('open', () => {
console.log('Connected to the
database');
});
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');
});