fs.promises in Node.js?fs.promises is a part of Node.js that provides file system methods which return promises. This lets you use async/await or .then() for easier asynchronous file operations.
fs.promises with async/await?You use await fs.promises.readFile(path, options) inside an async function. It returns the file content as a buffer or string if encoding is set.
Promises make code easier to read and write by avoiding nested callbacks. They allow chaining and use of async/await, which looks like normal synchronous code but runs asynchronously.
fs.promises.readFile?The promise is rejected with an error. You can catch this error using try/catch with async/await or .catch() when using promises.
fs.promises and logging its content.<pre>import { promises as fs } from 'fs';
async function readText() {
try {
const data = await fs.readFile('file.txt', 'utf8');
console.log(data);
} catch (err) {
console.error('Error reading file:', err);
}
}
readText();</pre>fs.promises reads a file asynchronously?readFile is the asynchronous method that returns a promise to read file contents.
fs.promises.readFile return when successful?It returns a promise that resolves with the file content as a buffer or string.
async/await with fs.promises.readFile?Errors from promises can be caught using try/catch when using async/await.
fs.promises in ES modules?In ES modules, import { promises as fs } from 'fs'; imports the promises API.
readFile to get a string instead of a buffer?Passing 'utf8' returns the file content as a string.
fs.promises and handle errors.