CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-parcel--utils

Node.js utility functions providing callback-to-promise conversion and error serialization for Parcel bundler

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

Parcel Utils

Parcel Utils provides essential Node.js utility functions for the Parcel bundler ecosystem. The package offers two core utilities: callback-to-promise conversion and error serialization, designed to support asynchronous programming patterns and cross-process communication in Parcel's multi-core compilation system.

Package Information

  • Package Name: @parcel/utils
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install @parcel/utils
  • Node.js Support: >= 6.0.0

Core Imports

const { promisify, errorUtils } = require('@parcel/utils');

Individual imports:

const promisify = require('@parcel/utils').promisify;
const errorUtils = require('@parcel/utils').errorUtils;

Basic Usage

const { promisify, errorUtils } = require('@parcel/utils');
const fs = require('fs');

// Convert callback-style function to promise
const readFile = promisify(fs.readFile);

// Use with async/await
async function readConfig() {
  try {
    const content = await readFile('config.json', 'utf8');
    return JSON.parse(content);
  } catch (error) {
    // Serialize error for cross-process communication
    const serializedError = errorUtils.errorToJson(error);
    console.log('Error details:', serializedError);
    
    // Later reconstruct the error
    const reconstructedError = errorUtils.jsonToError(serializedError);
    throw reconstructedError;
  }
}

Architecture

Parcel Utils is designed with version compatibility in mind:

  • Version Detection: Automatically uses native async functions on Node.js 8+ or compiled versions for Node.js 6-7
  • Module Structure: Two independent utilities accessed through named exports
  • Build System: Uses Babel for backward compatibility with older Node.js versions
  • Zero Dependencies: Pure utility library with no external runtime dependencies

Capabilities

Promise Conversion

Converts Node.js callback-style functions to Promise-based functions, enabling modern async/await patterns while maintaining compatibility with older callback conventions.

/**
 * Converts a callback-style function to a Promise-based function
 * @param {Function} fn - The callback-style function to promisify
 * @returns {Function} A new function that returns a Promise
 */
function promisify(fn: Function): Function;

The promisify function expects the callback to follow Node.js conventions:

  • Callback is the last parameter
  • Callback signature: (err, ...results) => void
  • If err is truthy, the Promise rejects with that error
  • If only one result is provided, Promise resolves with that single value
  • If multiple results are provided, Promise resolves with an array

Usage Examples:

const { promisify } = require('@parcel/utils');
const fs = require('fs');

// Promisify fs.readFile
const readFile = promisify(fs.readFile);

// Use with promises
readFile('package.json', 'utf8')
  .then(content => console.log(JSON.parse(content)))
  .catch(err => console.error('Error:', err));

// Use with async/await
async function loadPackageInfo() {
  const content = await readFile('package.json', 'utf8');
  return JSON.parse(content);
}

// Multiple results example (theoretical callback that returns multiple values)
const getMultipleValues = promisify((callback) => {
  callback(null, 'first', 'second', 'third');
});

// Results in array: ['first', 'second', 'third']
const values = await getMultipleValues();

Error Serialization

Provides robust error serialization and deserialization capabilities for converting errors to JSON format and reconstructing them. Essential for cross-process communication in Parcel's architecture.

/**
 * Converts an error to JSON-serializable format
 * @param {string|Error|any} error - String or Error object to convert
 * @returns {Object|undefined} Plain object representation of the error, or undefined for unsupported input types
 */
function errorToJson(error: string | Error | any): Object | undefined;

/**
 * Reconstructs an Error object from JSON representation
 * @param {Object} json - Plain object containing error data
 * @returns {Error|undefined} New Error object with properties restored, or undefined if json is falsy
 */
function jsonToError(json: Object): Error | undefined;

Error Serialization Behavior:

For string inputs:

  • Returns { message: string }

For Error objects:

  • Captures message, stack, and name properties
  • Preserves all custom properties (useful for error codes, context, etc.)
  • Maintains error metadata for debugging

For other input types:

  • Returns undefined implicitly (no explicit return for unsupported input types)

Error Reconstruction Behavior:

For valid JSON objects:

  • Creates new Error with message from JSON
  • Copies all properties from JSON to the Error object

For falsy inputs (null, undefined, empty string, etc.):

  • Returns undefined

Usage Examples:

const { errorUtils } = require('@parcel/utils');

// Serialize different error types
const stringError = errorUtils.errorToJson('Something went wrong');
// Result: { message: 'Something went wrong' }

const standardError = new Error('File not found');
const serialized = errorUtils.errorToJson(standardError);
// Result: { message: 'File not found', stack: '...', name: 'Error' }

// Custom error with additional properties
const customError = new Error('Parse error');
customError.code = 'PARSE_ERROR';
customError.line = 42;
customError.column = 15;

const serializedCustom = errorUtils.errorToJson(customError);
// Result: { message: 'Parse error', stack: '...', name: 'Error', code: 'PARSE_ERROR', line: 42, column: 15 }

// Reconstruct errors
const reconstructed = errorUtils.jsonToError(serializedCustom);
console.log(reconstructed instanceof Error); // true
console.log(reconstructed.code); // 'PARSE_ERROR'
console.log(reconstructed.line); // 42

// Cross-process communication example
function sendErrorToWorker(error) {
  const serialized = errorUtils.errorToJson(error);
  worker.postMessage({ type: 'error', error: serialized });
}

function receiveErrorFromWorker(message) {
  if (message.type === 'error') {
    const reconstructed = errorUtils.jsonToError(message.error);
    throw reconstructed; // Full Error object with all properties
  }
}

Types

// The errorUtils object with named functions
interface ErrorUtils {
  errorToJson(error: string | Error | any): Object | undefined;
  jsonToError(json: Object): Error | undefined;
}

// Main module exports
interface ParcelUtils {
  promisify: (fn: Function) => Function;
  errorUtils: ErrorUtils;
}

Install with Tessl CLI

npx tessl i tessl/npm-parcel--utils
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@parcel/utils@1.11.x
Publish Source
CLI
Badge
tessl/npm-parcel--utils badge