Pool2

1.4.1 · active · verified Wed Apr 22

Pool2 is a generic resource pooling library for Node.js, designed to efficiently manage expensive, reusable resources like database connections or network sockets. It provides a configurable framework for acquiring, releasing, disposing, and destroying resources, incorporating essential features such as minimum and maximum pool sizes, idle timeouts, request queuing, and health checks (ping functions). Key differentiators include its robust handling of resource lifecycle events and explicit timeouts for acquire and dispose operations, which helps prevent resource leaks and ensure application stability. The package is currently at version 1.4.1. While a specific release cadence isn't defined, the documentation indicates it's a mature and stable solution for resource management, offering fine-grained control over resource behavior and pooling strategies.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the basic creation of a resource pool, acquiring and releasing resources, and observing pool statistics. It includes custom acquire/dispose/destroy functions with asynchronous operations and pool shutdown.

const Pool = require('pool2');

// Simulate a resource that takes time to acquire and needs disposal
let resourceCounter = 0;

function createResource(id) {
  return {
    id: id,
    status: 'open',
    connect: () => new Promise(resolve => setTimeout(() => {
      console.log(`Resource ${id} connected.`);
      resolve();
    }, 100)),
    close: () => new Promise(resolve => setTimeout(() => {
      console.log(`Resource ${id} closed.`);
      resolve();
    }, 50)),
    destroy: () => {
      console.log(`Resource ${id} forcibly destroyed.`);
    }
  };
}

const pool = new Pool({
  acquire: function (cb) {
    const id = ++resourceCounter;
    const rsrc = createResource(id);
    rsrc.connect()
      .then(() => cb(null, rsrc))
      .catch(err => cb(err));
  },
  acquireTimeout: 5000,
  dispose: function (rsrc, cb) {
    rsrc.close()
      .then(() => cb())
      .catch(err => cb(err));
  },
  disposeTimeout: 2000,
  destroy: function (rsrc) {
    if (rsrc && rsrc.status === 'open') {
      rsrc.destroy();
    }
  },
  ping: function (rsrc, cb) {
    // Simple ping, assume resource is always alive for this example
    cb();
  },
  min: 1,
  max: 3,
  idleTimeout: 3000,
  syncInterval: 1000
});

async function usePool() {
  console.log('Acquiring resource...');
  let resource;
  try {
    resource = await new Promise((resolve, reject) => {
      pool.acquire((err, r) => {
        if (err) return reject(err);
        resolve(r);
      });
    });
    console.log(`Successfully acquired resource ${resource.id}. Doing work...`);
    await new Promise(resolve => setTimeout(resolve, 500)); // Simulate work
  } catch (err) {
    console.error('Failed to acquire resource:', err.message);
    return;
  } finally {
    if (resource) {
      console.log(`Releasing resource ${resource.id}.`);
      pool.release(resource);
    }
  }
  console.log('Current pool stats:', pool.stats());
}

(async () => {
  await usePool();
  await usePool();
  await usePool();

  console.log('Ending pool in 5 seconds...');
  setTimeout(() => {
    pool.end((errs) => {
      if (errs && errs.length > 0) {
        console.error('Errors during pool end:', errs);
      } else {
        console.log('Pool ended gracefully.');
      }
    });
  }, 5000);
})();

view raw JSON →