DEV Community

loading...

Use promises with almost any Node.js native modules

Amin
・1 min read

You are using a recent version of Node.js and are tired of working with callbacks with Node native modules.

Chances are, there is a version of that module that is using promises out of the box.

$ touch index.js
Enter fullscreen mode Exit fullscreen mode
const fs = require("fs").promises;

fs.readdir(process.cwd()).then(files => {
  console.log(files);
}).catch(error => {
  console.error(error.message);
});
Enter fullscreen mode Exit fullscreen mode
$ node index.js
Enter fullscreen mode Exit fullscreen mode

Or

$ touch index.mjs
Enter fullscreen mode Exit fullscreen mode
import {promises as fs} from "fs";

fs.readdir(process.cwd()).then(files => {
  console.log(files);
}).catch(error => {
  console.error(error.message);
});
Enter fullscreen mode Exit fullscreen mode
$ node index.mjs
Enter fullscreen mode Exit fullscreen mode

Discussion (0)