← Back to Node.js Course | Chapter 2: Core Modules | Lesson 5 of 7

util module

The util module collects handy helpers such as promisify, format and inspect.

In this page:

  1. util module
Syntax
javascript
const util = require('util');
const promisified = util.promisify(callbackFunction);
const result = await promisified(arg);

util module

util.promisify turns a callback-style function into one that returns a promise. util.format builds strings with placeholders and util.inspect prints objects with control over depth. util.types and util.isDeepStrictEqual help with checks.

Note: fs.promises already exists, so promisify is most useful for older callback APIs.

Example: util module

javascript
const util = require("util");
const wait = util.promisify((ms, cb) => setTimeout(() => cb(null, "done after " + ms), ms));
wait(10).then(console.log);
console.log(util.format("%s scored %d", "Ada", 95));
console.log(util.inspect({ a: { b: { c: 1 } } }, { depth: 0 }));

// Output:
// Ada scored 95
// { a: [Object] }
// done after 10

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Promisifying functions that do not follow the error-first callback convention
  2. Using deprecated util.isArray
  3. Logging deep objects and seeing [Object]
Chapter Summary
  • promisify converts callbacks to promises
  • format uses %s and %d placeholders
  • inspect controls object printing
  • Callbacks must be error-first
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.