DEV Community

Željko Šević
Željko Šević

Posted on • Originally published at sevic.dev on

Node.js built-in module functions as Promises

Node.js provides asynchronous methods for fs, dns, stream, and timers modules that return Promises.

const {
  createWriteStream,
  promises: { readFile }
} = require('fs');
const dns = require('dns/promises');
const stream = require('stream/promises');
const timers = require('timers/promises');
const sleep = timers.setTimeout;
const SLEEP_TIMEOUT_MS = 2000;

(async () => {
  const fileName = 'test-file';
  const writeStream = createWriteStream(fileName, {
    autoClose: true,
    flags: 'w'
  });
  await stream.pipeline('some text', writeStream);

  await sleep(SLEEP_TIMEOUT_MS);

  const readFileResult = await readFile(fileName);
  console.log(readFileResult.toString());

  const lookupResult = await dns.lookup('google.com');
  console.log(lookupResult);
})();
Enter fullscreen mode Exit fullscreen mode

Use the promisify function to convert other callback-based functions to Promise-based.

const crypto = require('crypto');
const { promisify } = require('util');
const randomBytes = promisify(crypto.randomBytes);
const RANDOM_BYTES_LENGTH = 20;

(async () => {
  const randomBytesResult = await randomBytes(RANDOM_BYTES_LENGTH);
  console.log(randomBytesResult);
})();
Enter fullscreen mode Exit fullscreen mode

Course

Build your SaaS in 2 weeks - Start Now

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay