Node.js Utility Functions: Your Swiss Army Knife 🔧
Imagine you have a magical toolbox. Inside it are special tools that help you fix, transform, and understand things. That’s exactly what the util module is in Node.js!
What is the Util Module?
Think of Node.js as a big kitchen. You have your main cooking tools (like fs for files, http for web). But sometimes you need helper gadgets—a timer, a magnifying glass, a translator.
The util module is that drawer of helper gadgets.
const util = require('util');
That’s it! Now you have access to all the helpers.
Why Do We Need It?
| Problem | Util Solution |
|---|---|
| Old callback code is messy | util.promisify makes it modern |
| Can’t see what’s inside an object | util.inspect shows everything |
| Need to convert text to bytes | TextEncoder does the magic |
| Have bytes, need text back | TextDecoder reverses it |
🪄 util.promisify: The Callback Transformer
The Story
Imagine you order pizza. In the old days, the pizza shop would call you back when ready. Annoying! You had to wait by the phone.
Now imagine a promise: “We’ll text you when it’s done.” You can do other things!
util.promisify transforms old “callback” functions into modern “promise” functions.
Before: The Callback Way (Messy)
const fs = require('fs');
fs.readFile('story.txt', (err, data) => {
if (err) {
console.log('Oops!', err);
return;
}
console.log(data);
});
See how the code goes sideways and nests? That’s “callback hell.”
After: The Promise Way (Clean)
const util = require('util');
const fs = require('fs');
const readFileAsync = util.promisify(fs.readFile);
async function readStory() {
const data = await readFileAsync('story.txt');
console.log(data);
}
readStory();
✅ Clean!
✅ Easy to read!
✅ Easy to handle errors with try/catch!
How It Works
graph TD A["Old Callback Function"] --> B["util.promisify"] B --> C["New Promise Function"] C --> D["Use with async/await"]
Quick Example
const util = require('util');
// Imagine a function that takes time
const setTimeout = util.promisify(global.setTimeout);
async function wait() {
console.log('Waiting...');
await setTimeout(2000);
console.log('Done waiting!');
}
wait();
🎯 Key Point: If a function uses (error, result) callbacks, you can promisify it!
🔍 util.inspect: The X-Ray Vision
The Story
You have a mystery box. You want to see everything inside—even the secret compartments. Normal looking doesn’t work. You need X-ray vision.
util.inspect gives you X-ray vision for JavaScript objects.
The Problem
const toy = {
name: 'Robot',
parts: {
head: { eyes: 2, color: 'blue' },
body: { arms: 2, legs: 2 }
}
};
console.log(toy);
// Shows: { name: 'Robot', parts: [Object] }
// Wait... what's inside [Object]?? 😤
The Solution
const util = require('util');
console.log(util.inspect(toy, {
depth: null, // Show ALL levels
colors: true // Pretty colors!
}));
Now you see everything!
Inspect Options
| Option | What It Does | Example |
|---|---|---|
depth |
How deep to look | depth: 2 or depth: null for all |
colors |
Pretty terminal colors | colors: true |
showHidden |
Show secret properties | showHidden: true |
compact |
Squeeze output together | compact: false for spread out |
Real Example
const util = require('util');
const user = {
name: 'Alex',
secret: Symbol('hidden'),
friends: [
{ name: 'Sam', age: 10 },
{ name: 'Jordan', age: 11 }
]
};
console.log(util.inspect(user, {
depth: null,
colors: true,
showHidden: true
}));
🎯 Key Point: When console.log shows [Object] or [Array], use util.inspect to see inside!
📝 TextEncoder: Words to Numbers
The Story
Computers don’t understand letters. They only understand numbers (specifically, 0s and 1s). When you type “Hello”, the computer secretly converts it to numbers.
TextEncoder is the translator from human text to computer bytes.
Simple Example
const encoder = new TextEncoder();
const text = 'Hi!';
const bytes = encoder.encode(text);
console.log(bytes);
// Uint8Array(3) [ 72, 105, 33 ]
Wait, what?
H= 72i= 105!= 33
That’s the ASCII code for each letter!
Why Do We Need This?
- Sending data over the internet → Data travels as bytes
- Saving to files → Files store bytes
- Encryption → Security works with bytes
- Working with binary data → Images, audio, etc.
The Flow
graph TD A["Hello 👋"] --> B["TextEncoder"] B --> C["72, 101, 108, 108, 111"] C --> D["Computer Understands!"]
Important Notes
- TextEncoder always uses UTF-8 (the universal language)
- The result is a
Uint8Array(a list of numbers 0-255) - Emojis work too! 😊 → Multiple bytes
const encoder = new TextEncoder();
console.log(encoder.encode('😊'));
// Uint8Array(4) [ 240, 159, 152, 138 ]
Emojis need 4 bytes because they’re special!
📖 TextDecoder: Numbers Back to Words
The Story
Now imagine you received a package with numbers: 72, 105, 33. What does it mean? You need a translator to decode it back to human words.
TextDecoder turns bytes back into text.
Simple Example
const decoder = new TextDecoder();
const bytes = new Uint8Array([72, 105, 33]);
const text = decoder.decode(bytes);
console.log(text);
// "Hi!"
Magic! The numbers became words again!
The Complete Round Trip
// Step 1: Human writes text
const message = 'Hello, World!';
// Step 2: Encode to bytes (for computer/network)
const encoder = new TextEncoder();
const bytes = encoder.encode(message);
console.log(bytes);
// Uint8Array of numbers
// Step 3: Decode back to text (for humans)
const decoder = new TextDecoder();
const result = decoder.decode(bytes);
console.log(result);
// "Hello, World!"
Different Languages
const decoder = new TextDecoder('utf-8');
// Works with any language!
const japanese = new TextEncoder().encode('こんにちは');
console.log(new TextDecoder().decode(japanese));
// "こんにちは"
Quick Reference
graph LR A["Text"] -->|TextEncoder| B["Bytes"] B -->|TextDecoder| C["Text"]
🎯 Summary: Your Utility Belt
| Tool | What It Does | When to Use |
|---|---|---|
util.promisify |
Converts callbacks → promises | Making old code modern |
util.inspect |
Deep view of objects | Debugging, logging |
TextEncoder |
Text → Bytes | Sending/saving data |
TextDecoder |
Bytes → Text | Reading received data |
Quick Code Cheat
const util = require('util');
// Promisify
const asyncFn = util.promisify(callbackFn);
// Inspect
console.log(util.inspect(obj, {
depth: null,
colors: true
}));
// Encode
const bytes = new TextEncoder().encode('text');
// Decode
const text = new TextDecoder().decode(bytes);
🌟 You Did It!
You now know how to:
✅ Transform old callback functions into modern promises ✅ See deep inside any JavaScript object ✅ Convert text to bytes for computers ✅ Convert bytes back to text for humans
These are your superpower tools. Use them wisely! 🦸♂️
