Node.js's util module for all engines providing cross-platform utility functions for formatting, type checking, inheritance, promises, and debugging.
—
Conversion tools between callback-based and promise-based function patterns, enabling modern async/await usage with legacy callback APIs and vice versa.
Converts a callback-based function to a promise-based function.
/**
* Converts a callback-based function to a promise-based function
* @param {Function} original - Function that takes a callback as its last parameter
* @returns {Function} Promise-based version of the original function
* @throws {TypeError} If original is not a function
*/
function promisify(original): Function;
/**
* Symbol for custom promisify implementations
*/
promisify.custom: symbol;The returned function will:
Usage Examples:
const util = require('util');
const fs = require('fs');
// Basic promisify
const readFileAsync = util.promisify(fs.readFile);
// Use with async/await
async function readConfig() {
try {
const data = await readFileAsync('config.json', 'utf8');
return JSON.parse(data);
} catch (error) {
console.error('Failed to read config:', error);
}
}
// Use with .then()
readFileAsync('package.json', 'utf8')
.then(data => JSON.parse(data))
.then(pkg => console.log(pkg.name))
.catch(err => console.error(err));
// Custom promisify implementation
function customReadFile(filename, callback) {
// Custom implementation
}
customReadFile[util.promisify.custom] = function(filename) {
return new Promise((resolve, reject) => {
// Custom promise logic
});
};
const promisifiedCustom = util.promisify(customReadFile);
// Will use the custom implementationConverts a promise-based function to a callback-based function.
/**
* Converts a promise-based function to a callback-based function
* @param {Function} original - Function that returns a Promise
* @returns {Function} Callback-based version of the original function
* @throws {TypeError} If original is not a function
*/
function callbackify(original): Function;The returned function will:
process.nextTick for proper Node.js callback semanticsUsage Examples:
const util = require('util');
// Promise-based function
async function fetchUserData(userId) {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return response.json();
}
// Convert to callback-based
const fetchUserDataCallback = util.callbackify(fetchUserData);
// Use with traditional callback pattern
fetchUserDataCallback(123, (err, userData) => {
if (err) {
console.error('Error fetching user:', err);
return;
}
console.log('User data:', userData);
});
// Another example with rejection handling
async function divideAsync(a, b) {
if (b === 0) {
throw new Error('Division by zero');
}
return a / b;
}
const divideCallback = util.callbackify(divideAsync);
divideCallback(10, 2, (err, result) => {
if (err) {
console.error('Error:', err.message);
} else {
console.log('Result:', result); // 5
}
});
divideCallback(10, 0, (err, result) => {
if (err) {
console.error('Error:', err.message); // "Division by zero"
}
});Both promisify and callbackify require Promises to be available:
reason propertyInstall with Tessl CLI
npx tessl i tessl/npm-util