Asynchronous FileSystem
As of Node.js 10 (released 2018), the FileSystem API (fs
) comes with promisified async versions of all the functions as well as blocking synchronous versions of them. Let's look at the same operation with all three alternatives.
fs.readFile
Many Node.js developers have worked with this API. This method will read a file, taking the file path as the first argument and a callback as the second argument. The callback will receive one or two arguments, an error (should one occur) as the first argument and a data buffer object as the second argument, should the read be successful:
import { readFile } from "fs"; import { resolve } from "path"; const filePath = resolve(__dirname, "text.txt"); readFile(filePath, (err, data) => { if (err) { throw err; } console.log(data.toString()); });
We read the file and log out the contents asynchronously. Anyone who...