hot-resource
v1.2.1
Published
[](https://www.npmjs.com/package/hot-resource) [](https://opensource.org/licenses/MIT)
Downloads
10,689
Readme
hot-resource
A lightweight TypeScript utility for managing resource lifecycle in Node.js and Bun applications. Hot Resource:
- 🔄 Creates resources on demand and cleans up automatically
- 🌟 Works with top-level await in modern JS/TS environments
- 🔥 Integrates seamlessly with Bun's hot module reload (
bun --hot) - 🧹 Handles application termination signals gracefully (SIGTERM, SIGINT)
- 🪶 Zero dependencies, TypeScript-first design
Installation
# Using npm
npm install hot-resource
# Using yarn
yarn add hot-resource
# Using bun
bun add hot-resourceUsage
Basic Example with Top-Level Await
import hotResource from "hot-resource";
// Database connection with cleanup function
export const db = await hotResource(async () => [
await connectToDatabase(),
async (connection) => {
await connection.close();
},
]);
// In another module, import your db directly at module scope, hot-resource will handle release
await db.query("SELECT * FROM users");
process.emit('SIGTERM') // notify close dbWith Disposable/AsyncDisposable
import hotResource from "hot-resource";
class MyResource {
async [Symbol.asyncDispose]() {
// Cleanup is automatic
}
}
const resource = await hotResource(() => new MyResource());Use with Bun's Hot Reloading
When running with bun --hot, hot-resource manages resources across hot reloads:
import hotResource from "hot-resource";
import { createServer } from "http";
// Server managed across hot reloads
const server = await hotResource(() => {
const server = createServer((req, res) => {
res.end("Hello from hot-reloaded server!");
});
server.listen(3000);
return [
server,
async (srv) => {
await new Promise(resolve => srv.close(resolve));
}
];
});API
hotResource<T>(create)
Creates or returns a cached resource and sets up automatic cleanup.
Parameters
create: Function that creates and returns one of:- A resource with Disposable/AsyncDisposable interface
- A tuple of
[resource, cleanupFunction]
Returns
Promise<T>- The created or cached resource
How It Works
- The resource is created once and cached in the global scope
- On Bun hot reload, existing resources are properly cleaned up
- On process termination (SIGTERM/SIGINT), all resources are released
- Resources with the same function signature are reused
Example Use Cases
- Database connections that auto-close on server shutdown
- HTTP/WebSocket servers that restart cleanly during development
- File watchers that properly release resources
- Any resource that needs lifecycle management
License
MIT © snomiao
