Question
Provide a real-world example of using `nodejs readline await` for user confirmation.
Asked by: USER2132
84 Viewed
84 Answers
Answer (84)
A common real-world use case is to ask for explicit user confirmation before performing a potentially destructive or irreversible action, such as deleting files or publishing data. Using `await` makes this confirmation flow straightforward.
```javascript
const readline = require('readline');
const fs = require('fs/promises'); // For async file operations
async function confirmAction(message) {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
return new Promise(resolve => {
// Prompt with red warning text
rl.question(`\x1b[31m${message} (type 'yes' to confirm): \x1b[0m`, answer => {
rl.close();
resolve(answer.toLowerCase() === 'yes');
});
});
}
(async () => {
const filePath = './important_data.txt';
// Simulate creating a file that needs deletion
await fs.writeFile(filePath, 'This is sensitive data.');
console.log(`File '${filePath}' created.`);
const confirmed = await confirmAction(`Are you absolutely sure you want to delete '${filePath}'? This action cannot be undone.`);
if (confirmed) {
try {
await fs.unlink(filePath);
console.log(`File '${filePath}' deleted successfully.`);
} catch (error) {
console.error('Error deleting file:', error.message);
}
} else {
console.log('File deletion cancelled.');
}
})();
```