A Node.js utility to ensure a function is called exactly once, with strict mode for error detection.
Once is a Node.js utility module that wraps functions to ensure they are executed exactly one time. It solves the common problem of accidental multiple callback invocations in asynchronous code, which can lead to bugs and unexpected behavior. The module caches the return value after the first call and returns it for all subsequent invocations.
Node.js developers working with asynchronous patterns, event listeners, or callbacks that should only fire once, such as in file loading, network requests, or initialization routines.
Developers choose Once for its simplicity, reliability, and dual modes—standard caching for safety and strict mode for debugging. It's a lightweight, dependency-free solution that integrates easily into existing codebases.
Run a function exactly one time
Open-Awesome is built by the community, for the community. Submit a project, suggest an awesome list, or help improve the catalog on GitHub.
The module has zero dependencies, keeping the package minimal and reducing bloat, as emphasized in its philosophy of solving the single-use problem cleanly.
Offers both permissive caching with once() and strict error-throwing with once.strict(), allowing developers to choose between safety and debugging, as shown in the greet function example.
Provides fn.called and fn.value properties to check invocation status and retrieve cached results, aiding in control flow and debugging, as documented in the usage section.
Can be used directly or via Function.prototype extension for chaining, making it simple to wrap callbacks in existing Node.js code, though the prototype feature adds complexity.
Primarily designed for Node.js callbacks; it doesn't natively support modern async functions or Promises, requiring additional wrapping for contemporary async code.
The optional proto() method extends Function.prototype, which can cause conflicts in larger codebases or with other libraries, as ironically noted in the README.
Once caches only the first call's result, ignoring arguments; it's unsuitable for functions where different inputs should produce different outputs, limiting memoization use cases.