Using the fs.promises API

Node.js 10 introduced the fs.promises API, providing a promise-based approach to file system operations.

javascriptCopy code// Example using fs.promises for file operations
const fs = require('fs').promises;

async function manageFile() {
try {
    await fs.writeFile('./example.txt', 'Hello, Node.js!');
    const data = await fs.readFile('./example.txt', 'utf8');
    console.log('File content:', data);
    await fs.unlink('./example.txt');
    console.log('File deleted.');
} catch (err) {
    console.error('Error managing file:', err);
}
} manageFile();

Explanation:

  • Perform file operations (write, read, delete) using the promise-based fs.promises API.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *