How Node really works · Chapter 26 of 34
Util
By the end of this chapter you can turn callback code into promises, log any value in full, read command line flags and compare nested objects, all with node:util. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: The system
- 6 tasks
- Node.js
- In the all labs plan
The first 2 chapters of How Node really works are free. This one comes with the all labs plan.
Why you need this
Ravi's stock service was written by a freelancer in 2019: every function takes a callback, and nobody wants to touch it. The new report scripts all use async and await, the logs are full of [Object] where the interesting part of an order should be, and the payments team needs to spot an order that was paid twice.
You could wrap every callback in a promise by hand, write a flag parser, and compare objects key by key, and each would have its own bugs. node:util already has all of these. Check it before you install a package.
What you build: 6 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
getStock: turn the old stock lookup into a promise
Export getStock(item), the promise version of lookupStock, made with util.promisify. Calling it returns a promise that resolves with the count (getStock('cutting chai') resolves to 300) and rejects with lookupStock's own error, Unknown item: <item>, for an item it does not know.
- Task 2
printTicket: teach promisify about the kitchen printer
printTicket calls back with two results, (null, jobId, pages), and plain promisify keeps only the first. Give printTicket a function under the promisify.custom symbol that takes the text and returns a promise of exactly { jobId, pages }, or rejects with the printer's error (Nothing to print for empty text).
promisify(printTicket) must then return that very function, and printTicket itself must still work with a callback, as before.
- Task 3
logLine: one clear log line for any value
Write logLine(label, value). It returns [label] followed by a space and the value: logLine('stock', { chai: { left: 3 } }) returns '[stock] { chai: { left: 3 } }'.
An error becomes Name: message, without the stack, and that includes an error made in another realm (from node:vm) that is not instanceof Error. A promise makes logLine throw a TypeError, because someone forgot to await it. Anything else is shown by util.inspect in full, however deeply nested (never [Object]), on one single line, without colour codes.
- Task 4
parseReportArgs: read the nightly report's flags
Write parseReportArgs(argv), where argv is the list of words after the script name. Read them with util.parseArgs and return exactly { date, format, verbose, items }.
--date or -d is a string and is required: without it, throw an Error whose message mentions date. --format (no short form, and --format=json works too) is text when left out, and json or csv otherwise; any other value throws an Error whose message mentions format. --verbose or -v is a boolean, false when left out. --item or -i is a string that may repeat; items lists them in order, and is [] when there are none.
An unknown flag, or a word that is not a flag (a positional argument), throws.
- Task 5
isDuplicateOrder: spot the same UPI order paid twice
Write isDuplicateOrder(a, b). It returns true when the two orders are the same apart from their id and placedAt, compared deeply and strictly: 2 and '2' differ, the order of keys does not matter, the order of items in an array does, and an extra key holding undefined makes them different.
It must not change either order.
- Task 6 · interview question
Interview: myPromisify, write your own promisify
Write myPromisify(fn) without util.promisify. It returns a function that returns a promise. That function calls fn with all its own arguments plus one callback as the last argument, and nothing else. The callback rejects the promise with its error, or resolves it with the first value only.
this must be kept: when the returned function is stored on an object and called as a method, fn runs with that object as this.
What you will learn
- promisify: turn an error-first callback function into one that returns a promise, including the custom version and this.
- inspect, format and types: print any value in full on one line, and recognise errors and promises reliably.
- parseArgs: command line flags without a package.
- isDeepStrictEqual: compare nested values by content.
More in The system
Build "Util" yourself
Tapri’s order server must never stall at the 4 pm rush. You learn why it would. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of How Node really works are free. This one comes with the all labs plan.