Explain Codes LogoExplain Codes Logo

Using filesystem in node.js with async / await

javascript
async-await
fs-promises
node-js
Alex KataevbyAlex Kataev·Dec 24, 2024
TLDR

In the new world of Node.js, fs.promises are your best friends for async/await file operations. Let's break it down:

const fs = require('fs/promises'); async function readAsync(file) { try { // Reading like a boss with async/await console.log(await fs.readFile(file, 'utf8')); } catch (err) { // Oops! Error, but we've got it covered console.error('Read error', err); } } // RUNNING: Let's give this baby a whirl readAsync('path/to/file.txt');

Ensure: Your Node version is >= 10 for fs.promises. This method simplifies asynchronous file reading whilst waving goodbye to callbacks.

Realizing the power of import

With the advent of the fs/promises module in Node.js, cleaner and more readable async file system operations are no more a dream. Directly access promisified file system methods with a simple import and say goodbye to manually promisifying callbacks:

// Modern importing, cooler coding! const fs = require('fs/promises');

Master directory navigation

Here's how fs.promises.readdir coupled with async/await can simplify your filesystem operations and make error handling as easy as pie:

// DIRECTORY: We've got this! async function listFilesInDirectory(directoryPath) { try { // Listing files without breaking a sweat const files = await fs.readdir(directoryPath); console.log(`Files in ${directoryPath}:`, files); } catch (err) { // Error handling like a pro console.error('Error listing files', err); } } // RUNNING: Let's list 'em out listFilesInDirectory('./path/to/directory');

Write files like a champ

Experience writing to a file like you never did before, thanks to async/await:

// WRITE: We're writing the future async function writeToFile(filePath, contents) { try { // Writing done right await fs.writeFile(filePath, contents); console.log(`File written successfully at ${filePath}`); } catch (err) { // Always prepared for the unexpected console.error('Error writing file', err); } } // RUNNING: Let's write some epic history writeToFile('path/to/output.txt', 'Hello World!');

Do remember to define the file encoding, such as 'utf8', especially for text files to steer clear of possible issues.

Unleashing the full potential

The fs/promises module delivers a wide range of asynchronous file operations. Move beyond reading and writing:

  • fs.promises.copyFile to duplicate files—think copy-paste but for files
  • fs.promises.mkdir to create directories—building your file structure castle
  • fs.promises.unlink to delete files—goodbye, unwanted data

Combine these methods with async/await to handle file operations in a linear, comprehensible manner while keeping the non-blocking I/O as an ally.

Handling exceptions, no sweat

The beauty of async/await is the privilege to use try/catch for handling exceptions. This provides a clear flow of control and uniform error handling across various file operations. No more juggling callbacks!

The codes of modern Node.js

If you're working on an older version of Node.js, considering upgrading to enjoy the benefits of the fs/promises API. While you can use util.promisify for older versions, the transition to native promises is high on recommendation for cleaner code and improved error handling.

Code legibility is king

Structuring your code with async/await and fs/promises enhances its comprehension and maintainability, a boon for your team (or future you). Consistent structure like using arrow functions and appropriate function definitions contributes to an uncluttered codebase.