npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

defer-node-js

v0.7.0

Published

Defer and recover for JavaScript and TypeScript, inspired by Golang. defer lets you schedule cleanup functions to run after a parent function exits, ensuring efficient resource management. recover helps handle errors gracefully, making them ideal for robu

Downloads

3

Readme

defer-node-js

Defer and recover for JavaScript and TypeScript, inspired by Golang. defer lets you schedule cleanup functions to run after a parent function exits, ensuring efficient resource management. recover helps handle errors gracefully, making them ideal for robust error handling and resource cleanup in complex workflows.

install

npm i defer-node-js

Introduction

In go, the defer keyword schedules a function call to be run when the parent exit. Weather by reaching the end of the funciton or by a panic. The recover function in go stops the panic and returns the error value inside the defered block.

Javascript doesn't have built-in language feature for defer or recover. Instead, developers often rely on try/finally to construct or explicit cleanup calls.

This library emulates Go's defer and recover for blocking and non-blocking functions.

Goals

  1. Resource management: Provide a simpler pattern for resource cleanup without scattering finally blocks trhoughout your code.
  2. Error handling: Allow centeral point to catch and " recover " from error that happened in the main function.

Architecture

  1. Defer stack (LIFO): We maintain a stack of deferred functions. When .defer(fn) is called, fn is pushed into the stack.

  2. .wrapper:

  • The wrapper method returns a new function that when invoked setups the ( deferr environment) which is managed stack within js stack.
  • it calls the original function capturing any errors.
  • It then executes all the defered functions LIFO.
  • If no defered funcations calls recover, the original error is rethrown.
  1. Recover: if a defered function calls .recover() and the parent function thrown an error, the bottom defered function will nullifies the error, the error is swallowed and returns with the recover() method.

Typical use-cases

  1. File handling
import fs from 'fs';
import { SyncDeferer } from 'defer';

const readFileSafely = SyncDeferer.wrapper((filePath: string) => {
  // open file
  const fd = fs.openSync(filePath, 'r');
  // always close file when the function returns or throws
  SyncDeferer.defer(() => fs.closeSync(fd));

  const content = fs.readFileSync(fd, 'utf-8');
  return content;
});

try {
  const data = readFileSafely('/path/to/file.txt');
  console.log('File data:', data);
} catch (error) {
  console.error('Failed to read file:', error);
}
  1. Networking and socket cleanup
import net from 'net';
import { AsyncDeferer } from 'defer';

const defer = new AsyncDeferer();

const handleConnection = defer.wrapper((socket: net.Socket) => {
  // schedule a cleanup
  defer.defer(() => socket.end());

  // do some I/O
  socket.write('Hello from server!');
  // possibly more code ...
});
  1. Error recovery handling example :
import { SyncDeferer } from 'defer';

const faultyFunction = SyncDeferer.wrapper(() => {
  // schedule a deferred function that recovers from error
  SyncDeferer.defer(() => {
    const err = Deferer.recover();
    if (err) {
      console.log('Recovered from error:', err);
    }
  });

  // Now deliberately throw an error
  throw new Error('Something went wrong...');
});

// This call will NOT crash the program; it recovers inside the deferred function
faultyFunction();
console.log("Program continues after recovered error!");