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

utilities.mddocs/

Utilities

Core utility functions for inheritance, deprecation warnings, debugging, object extension, and timestamp logging.

Capabilities

Inheritance

Classical inheritance helper for constructor functions.

/**
 * Inherit prototype methods from one constructor into another
 * @param {Function} ctor - Constructor function which needs to inherit the prototype
 * @param {Function} superCtor - Constructor function to inherit prototype from
 */
function inherits(ctor, superCtor): void;

Sets up prototype chain so that ctor instances inherit from superCtor.prototype. This is a standalone version of the inheritance pattern, not dependent on Function.prototype.

Usage Examples:

const util = require('util');
const EventEmitter = require('events');

// Define a custom class
function MyEmitter() {
  EventEmitter.call(this);
}

// Set up inheritance
util.inherits(MyEmitter, EventEmitter);

// Add custom methods
MyEmitter.prototype.greet = function(name) {
  this.emit('greeting', `Hello, ${name}!`);
};

// Usage
const emitter = new MyEmitter();
emitter.on('greeting', (message) => {
  console.log(message);
});
emitter.greet('World'); // Emits: "Hello, World!"

// Verify inheritance
console.log(emitter instanceof MyEmitter); // true
console.log(emitter instanceof EventEmitter); // true

Deprecation

Function wrapper that emits deprecation warnings.

/**
 * Wraps a function to emit deprecation warnings when called
 * @param {Function} fn - Function to wrap
 * @param {string} msg - Deprecation message
 * @returns {Function} Wrapped function that warns on first call
 */
function deprecate(fn, msg): Function;

Behavior depends on Node.js process flags:

  • process.noDeprecation === true: Returns original function without warnings
  • process.throwDeprecation === true: Throws error instead of warning
  • process.traceDeprecation === true: Prints stack trace with warning
  • Default: Prints warning to stderr on first call

Usage Examples:

const util = require('util');

// Deprecate a function
function oldFunction() {
  return 'This is deprecated';
}

const deprecatedFunction = util.deprecate(
  oldFunction,
  'oldFunction is deprecated. Use newFunction instead.'
);

// First call shows warning, subsequent calls are silent
deprecatedFunction(); // Shows warning + returns result
deprecatedFunction(); // Only returns result

// Example with replacement suggestion
const oldAPI = util.deprecate(
  function(data) {
    return processLegacyData(data);
  },
  'oldAPI is deprecated. Use newAPI with updated parameters.'
);

Debug Logging

Conditional debug logging based on NODE_DEBUG environment variable.

/**
 * Creates a debug logging function for the specified module
 * @param {string} set - Debug namespace/module name
 * @returns {Function} Debug logging function (noop if not enabled)
 */
function debuglog(set): Function;

Returns a logging function that only outputs when NODE_DEBUG environment variable includes the specified set name. Supports wildcards and comma-separated lists.

Usage Examples:

const util = require('util');

// Create debug logger
const debug = util.debuglog('mymodule');

// Use debug logger (only outputs if NODE_DEBUG includes 'mymodule')
debug('Starting initialization');
debug('Processing item %s', itemName);

// Environment variable examples:
// NODE_DEBUG=mymodule node app.js          // Shows mymodule logs
// NODE_DEBUG=mymodule,http node app.js     // Shows mymodule and http logs  
// NODE_DEBUG=* node app.js                 // Shows all debug logs
// NODE_DEBUG=my* node app.js               // Shows logs matching my*

// Multiple debug loggers
const httpDebug = util.debuglog('http');
const dbDebug = util.debuglog('database');

httpDebug('HTTP request received');
dbDebug('Database query executed');

Object Extension

Extends an object with properties from another object.

/**
 * Extends an object with properties from another object
 * @param {Object} origin - Target object to extend
 * @param {Object} add - Source object to copy properties from
 * @returns {Object} The extended origin object
 */
function _extend(origin, add): Object;

Copies enumerable own properties from add to origin. Returns the origin object. If add is not an object, returns origin unchanged.

Usage Examples:

const util = require('util');

// Basic extension
const defaults = { timeout: 5000, retries: 3 };
const options = { timeout: 10000 };

const config = util._extend(defaults, options);
console.log(config); // { timeout: 10000, retries: 3 }

// Extension with null/undefined (returns origin unchanged)
const base = { a: 1 };
util._extend(base, null); // { a: 1 }
util._extend(base, undefined); // { a: 1 }

// Modifies original object
const original = { x: 1 };
const result = util._extend(original, { y: 2 });
console.log(original === result); // true
console.log(original); // { x: 1, y: 2 }

Timestamp Logging

Console logging with timestamp prefix.

/**
 * Logs to console with timestamp prefix
 * @param {...any} args - Arguments to log (same as console.log)
 */
function log(...args): void;

Outputs to console.log with a timestamp in "DD MMM HH:MM:SS" format. Arguments are formatted using the format function.

Usage Examples:

const util = require('util');

// Basic logging with timestamp
util.log('Server started');
// Output: "5 Dec 14:30:15 - Server started"

// Multiple arguments
util.log('User %s logged in from %s', 'alice', '192.168.1.1');
// Output: "5 Dec 14:30:16 - User alice logged in from 192.168.1.1"

// Objects are inspected
util.log('Config loaded:', { port: 3000, env: 'production' });
// Output: "5 Dec 14:30:17 - Config loaded: { port: 3000, env: 'production' }"

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