util module
The util module collects handy helpers such as promisify, format and inspect.
In this page:
Syntax
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
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
- Promisifying functions that do not follow the error-first callback convention
- Using deprecated util.isArray
- 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: