CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-util

Node.js's util module for all engines providing cross-platform utility functions for formatting, type checking, inheritance, promises, and debugging.

Pending
Overview
Eval results
Files

promises.mddocs/

Promise Utilities

Conversion tools between callback-based and promise-based function patterns, enabling modern async/await usage with legacy callback APIs and vice versa.

Capabilities

Promisify Function

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:

  • Return a Promise instead of using a callback
  • Pass all arguments to the original function except the callback
  • Resolve with the callback's second argument (success value)
  • Reject with the callback's first argument (error value)

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 implementation

Callbackify Function

Converts 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:

  • Take a callback as its last parameter
  • Call the original function with all other arguments
  • Call the callback with (error, result) based on Promise resolution/rejection
  • Use process.nextTick for proper Node.js callback semantics

Usage 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"
  }
});

Promise Requirements

Both promisify and callbackify require Promises to be available:

  • Native Promises (Node.js 4+ or modern browsers)
  • Polyfill such as es6-promise for older environments

Error Handling Patterns

Promisify Error Handling

  • Callback errors (first parameter) become Promise rejections
  • Callback results (second parameter) become Promise resolutions
  • Synchronous exceptions in the original function become rejections

Callbackify Error Handling

  • Promise rejections become callback errors (first parameter)
  • Promise resolutions become callback results (second parameter)
  • Falsy rejection values are wrapped in Error objects with a reason property

Install with Tessl CLI

npx tessl i tessl/npm-util

docs

index.md

promises.md

string-formatting.md

type-checking.md

utilities.md

tile.json