Blog>
Snippets

Handling File I/O with fs Promises

Demonstrate reading and writing to a file using the fs.promises API in a non-blocking way.
// Import the fs module with promises
const fs = require('fs').promises;

// Function to read a file asynchronously
async function readFile(filepath) {
  try {
    // Read the file's contents and return them
    const data = await fs.readFile(filepath, 'utf8');
    return data;
  } catch (error) {
    // Handle any errors while reading the file
    console.error(`Failed to read file at ${filepath}:`, error);
  }
}
This piece of code demonstrates how to read from a file asynchronously using the fs promises API. It defines an async function named readFile that takes a filepath as an argument, reads the file's contents using fs.readFile, and returns the data or logs an error if one occurs.
// Function to write data to a file asynchronously
async function writeFile(filepath, data) {
  try {
    // Write the data to the file
    await fs.writeFile(filepath, data);
    console.log(`Data written to ${filepath} successfully`);
  } catch (error) {
    // Handle any errors while writing to the file
    console.error(`Failed to write to file at ${filepath}:`, error);
  }
}
This piece of code shows how to write data to a file asynchronously using the fs promises API. It defines an async function named writeFile that takes a filepath and data as arguments, writes the data to the file with fs.writeFile, and logs a success message or an error message in case of failure.
// Example usage
(async () => {
  const filePath = './example.txt';
  const dataToWrite = 'Hello, world!';

  // Write data to the file
  await writeFile(filePath, dataToWrite);

  // Read the data back from the file
  const dataRead = await readFile(filePath);
  console.log(`Data read from file: ${dataRead}`);
})();
This piece of code is an example of how to use the readFile and writeFile functions created earlier. It is wrapped in an IIFE (Immediately Invoked Function Expression) that is marked as async to allow the use of await. The code writes 'Hello, world!' to a file named 'example.txt' and then reads the content back from the same file, logging the result to the console.