Almost one year ago, Node 8 was released. It was a major
release and brought quite a bit of ESnext
to the masses. Even then, back in
June I recognized that one of the major pitfalls when working with Node are
the callback-based APIs that (IMHO) pollute your code.
Somewhat hidden in that release, was util.promisify
, a native way of converting
an errback
(or Node-style callback) into a Promise
.
Node 8 released https://t.co/VI5ksS9vl8 // I'm a simple person, util.promisify is my fav 😹
— Adrian Perez (@blackxored) June 1, 2017
fs
As Node 10 just landed a few days ago, I was excited to see the most common case for such an util (dealing with filesystem APIs) was being addressed in some fashion.
While marked as experimental, it means that we can now use promises (and as you might have guessed async/await
)
when dealing with the filesystem.
Unfortunately, this hasn't landed in the original module, which means you need
to change your imports to fs/promises
. You will also get this warning:
(node:95830) ExperimentalWarning: The fs/promises API is experimental
Here's an example, leveraging latest JavaScript (sans modules):
const fs = require('fs/promises');
const readConfig = async (configFile) => {
try {
const config = await fs.readFile(configFile, 'utf-8');
// do something with file contents
} catch (e) {
throw new Error(`Failed to load config file at ${configFile}`);
}
}
You can access the documentation for the fs Promises API on this page, but if you're eager to see what's supported here's a list for your convenience (sort-of sorted by popularity):
readFile
writeFile
write
copyFile
open
read
rename
mkdir
rmdir
fstat
readlink
unlink
mkdtemp
access
truncate
ftruncate
fdatasync
fsync
readdir
symlink
lstat
stat
link
fchmod
chmod
lchmod
lchown
fchown
utimes
futimes
realpath
appendFile
So, it took us quite a while, but finally we got Promises somewhere it matters. I can only hope that this extends more and more into Node core, and we might have a shot against callback hell. It only took 10 major versions, but I'm hopeful.
What's that? What about observables, you say? Well...