Node fs module async/await
December 14, 2020
·Usually when working with the Node fs
module you need to decide between using the synchronous methods or the asynchronous methods with callbacks. The synchronous version could look like this:
import fs from 'fs'
const files = fs.readdirSync(path.join(process.cwd(), 'content'))
and the asynchronous version could look like this:
import fs from 'fs'
const files = fs.readdir(path.join(process.cwd(), 'content'), (err, files) => { ... }
I've always seen developers recommend using the asynchronous version for performance reasons (non-blocking), however many still reach for the synchronous version to avoid callback hell and because it's easier to reason about.
I recently learned that as of Node 12 a Promise version of the functions is available as part of the standard library. You could use this in combination with async/await for a version that is non-blocking and easy to reason about. The best of aspects of both.
import { promises as fs } from 'fs'
const files = await fs.readdir(path.join(process.cwd(), 'content'))