const fs = require('fs');
const path = require('path');
// Function to simulate writing to a file with potential errors
function writeWithErrorHandling(filename, data, shouldError = false) {
return new Promise((resolve, reject) => {
// Create a write stream
const writeStream = fs.createWriteStream(filename);
// Handle errors
writeStream.on('error', (err) => {
console.error(`Error writing to ${filename}: ${err.message}`);
reject(err);
});
// Handle finish event
writeStream.on('finish', () => {
console.log(`Successfully wrote to ${filename}`);
resolve();
});
// Write data
writeStream.write(data);
// Simulate an error if requested
if (shouldError) {
// Force an error by trying to write to a closed stream
writeStream.destroy(new Error('Simulated write error'));
} else {
// End the stream normally
writeStream.end();
}
});
}
// Function to demonstrate error handling with callbacks
function writeWithCallbacks() {
const filename = path.join(__dirname, 'callback-example.txt');
const writeStream = fs.createWriteStream(filename);
console.log('\n--- Testing error handling with callbacks ---');
// Write some data
writeStream.write('First chunk\n');
// Handle errors
writeStream.on('error', (err) => {
console.error(`Error in callback example: ${err.message}`);
});
// Simulate an error
writeStream.destroy(new Error('Simulated error in callback example'));
// This will cause an error but won't crash the process
writeStream.write('This will cause an error\n');
}
// Function to demonstrate error handling with promises
async function writeWithPromises() {
console.log('\n--- Testing error handling with Promises ---');
try {
// This will succeed
await writeWithErrorHandling('success.txt', 'This is a test\n');
// This will fail
await writeWithErrorHandling('/invalid/path/test.txt', 'This should fail\n', true);
} catch (err) {
console.error(`Caught error in promise chain: ${err.message}`);
}
}
// Function to demonstrate error handling with async/await
async function writeWithAsyncAwait() {
console.log('\n--- Testing error handling with async/await ---');
try {
// This will succeed
await writeWithErrorHandling('async-success.txt', 'Async test data\n');
// This will throw an error
const writeStream = fs.createWriteStream('async-error.txt');
writeStream.destroy(new Error('Simulated async error'));
// This will throw an error
await new Promise((resolve, reject) => {
writeStream.write('This will fail', (err) => {
if (err) {
console.error('Async write error:', err.message);
reject(err);
} else {
resolve();
}
});
});
} catch (err) {
console.error(`Caught error in async/await: ${err.message}`);
}
}
// Run all examples
async function runExamples() {
try {
// Test with callbacks
writeWithCallbacks();
// Test with Promises
await writeWithPromises();
// Test with async/await
await writeWithAsyncAwait();
} catch (err) {
console.error('Unhandled error in runExamples:', err.message);
}
}
// Clean up any existing test files
function cleanup() {
const filesToRemove = [
'success.txt',
'async-success.txt',
'async-error.txt',
'callback-example.txt'
];
filesToRemove.forEach(file => {
if (fs.existsSync(file)) {
try {
fs.unlinkSync(file);
console.log(`Removed test file: ${file}`);
} catch (err) {
console.error(`Error removing ${file}:`, err.message);
}
}
});
}
// Run the examples and clean up when done
runExamples()
.then(() => {
console.log('\nAll examples completed');
cleanup();
})
.catch(err => {
console.error('Error running examples:', err);
cleanup();
});