Protected
_debugProtected
Optional
_parentParent context
Protected
configConfiguration resolver
Readonly
nameName of the context
Protected
Readonly
registryKey to binding map as the internal registry
Readonly
requestReadonly
responseA flag to tell if the response is finished.
Scope for binding resolution
Optional
sessionReadonly
subscriptionManager for observer subscriptions
Protected
Readonly
tagIndexer for bindings by tag
Internal
Getter for ContextSubscriptionManager
Protected
_findFind bindings by tag leveraging indexes
Tag name pattern or name/value pairs
Protected
_mergeOptional
[captureAdd a binding to the context. If a locked binding already exists with the same key, an error will be thrown.
The configured binding to be added
Close the context: clear observers, stop notifications, and remove event listeners from its parent context.
Create a corresponding binding for configuration of the target bound by the given key in the context.
For example, ctx.configure('controllers.MyController').to({x: 1})
will
create binding controllers.MyController:$config
with value {x: 1}
.
Optional
key: BindingAddressThe key for the binding to be configured
Check if a binding exists with the given key in the local context without delegating to the parent context
Binding key
Create a view of the context chain with the given binding filter
A function to match bindings
Optional
comparator: BindingComparatorA function to sort matched bindings
Optional
options: Omit<ResolutionOptions, "session">Resolution options
Protected
debugWrap the debug statement so that it always print out the context name as the prefix
Arguments for the debug
Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
to each.
Returns true
if the event had listeners, false
otherwise.
import { EventEmitter } from 'node:events';
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
Emit an error
event
Error
A strongly-typed method to emit context events
Event type
Context event
Returns an array listing the events for which the emitter has registered
listeners. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
Find bindings using a key pattern or filter function
Optional
pattern: string | RegExp | BindingFilterA filter function, a regexp or a wildcard pattern with
optional *
and ?
. Find returns such bindings where the key matches
the provided pattern.
For a wildcard:
*
matches zero or more characters except .
and :
?
matches exactly one character except .
and :
For a filter function:
true
to include the binding in the resultsfalse
to exclude it.Find bindings using the tag filter. If the filter matches one of the binding tags, the binding is included.
A filter for tags. It can be in one of the following forms:
/controller/
*
and ?
, such as 'con*'
For a wildcard:
*
matches zero or more characters except .
and :
?
matches exactly one character except .
and :
{name: 'my-controller'}
Get the value bound to the given key, throw an error when no value is bound for the given key.
The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.
Optional
session: ResolutionSessionOptional session for resolution (accepted for backward compatibility)
A promise of the bound value.
// get the value bound to "application.instance"
const app = await ctx.get<Application>('application.instance');
// get "rest" property from the value bound to "config"
const config = await ctx.get<RestComponentConfig>('config#rest');
// get "a" property of "numbers" property from the value bound to "data"
ctx.bind('data').to({numbers: {a: 1, b: 2}, port: 3000});
const a = await ctx.get<number>('data#numbers.a');
Get the value bound to the given key, optionally return a (deep) property of the bound value.
The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.
Options for resolution.
A promise of the bound value, or a promise of undefined when the optional binding is not found.
Look up a binding by key in the context and its ancestors. If no matching
binding is found and options.optional
is not set to true, an error will
be thrown.
Binding key
Optional
options: { optional?: boolean }Options to control if the binding is optional. If
options.optional
is set to true, the method will return undefined
instead of throwing an error if the binding key is not found.
Resolve configuration for the binding by key
Binding key
Optional
propertyPath: stringProperty path for the option. For example, x.y
requests for <config>.x.y
. If not set, the <config>
object will be
returned.
Optional
resolutionOptions: ResolutionOptionsOptions for the resolution.
Get the value or promise of configuration for a given binding by key
Binding key
Optional
propertyPath: stringProperty path for the option. For example, x.y
requests for <config>.x.y
. If not set, the <config>
object will be
returned.
Optional
resolutionOptions: ResolutionOptionsOptions for the resolution.
true
, undefined
will be returned if
no corresponding value is found. Otherwise, an error will be thrown.Resolve configuration synchronously for the binding by key
Binding key
Optional
propertyPath: stringProperty path for the option. For example, x.y
requests for config.x.y
. If not set, the config
object will be
returned.
Optional
resolutionOptions: ResolutionOptionsOptions for the resolution.
Protected
getGet the owning context for a binding or its key
Binding object or key
Locate the resolution context for the given binding. Only bindings in the resolution context and its ancestors are visible as dependencies to resolve the given binding
Binding object
Get the context matching the scope
Binding scope
Get the synchronous value bound to the given key, optionally return a (deep) property of the bound value.
This method throws an error if the bound value requires async computation (returns a promise). You should never rely on sync bindings in production code.
The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.
Optional
session: ResolutionSessionSession for resolution (accepted for backward compatibility)
A promise of the bound value.
Get the synchronous value bound to the given key, optionally return a (deep) property of the bound value.
This method throws an error if the bound value requires async computation (returns a promise). You should never rely on sync bindings in production code.
The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.
Optional
options: ResolutionOptionsOptions for resolution.
The bound value, or undefined when an optional binding is not found.
Internal
Get the value bound to the given key.
This is an internal version that preserves the dual sync/async result
of Binding#getValue()
. Users should use get()
or getSync()
instead.
The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.
Optional
optionsOrSession: ResolutionOptionsOrSessionOptions for resolution or a session
The bound value or a promise of the bound value, depending on how the binding is configured.
// get the value bound to "application.instance"
ctx.getValueOrPromise<Application>('application.instance');
// get "rest" property from the value bound to "config"
ctx.getValueOrPromise<RestComponentConfig>('config#rest');
// get "a" property of "numbers" property from the value bound to "data"
ctx.bind('data').to({numbers: {a: 1, b: 2}, port: 3000});
ctx.getValueOrPromise<number>('data#numbers.a');
Inspect the context and dump out a JSON object representing the context hierarchy
Optional
options: ContextInspectOptionsOptions for inspect
Check if a key is bound in the context or its ancestors
Binding key
Check if an observer is subscribed to this context
Context observer
Check if this context is visible (same or ancestor) to the given one
Another context object
Returns the number of listeners listening for the event named eventName
.
If listener
is provided, it will return how many times the listener is found
in the list of the listeners of the event.
The name of the event being listened for
Optional
listener: FunctionThe event handler function
Returns a copy of the array of listeners for the event named eventName
.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
The "bind" event is emitted when a new binding is added to the context. The "unbind" event is emitted when an existing binding is removed.
The name of the event - always bind
or unbind
.
The listener function to call when the event is emitted.
The "bind" event is emitted when a new binding is added to the context. The "unbind" event is emitted when an existing binding is removed.
The listener function to call when the event is emitted.
The "bind" event is emitted when a new binding is added to the context. The "unbind" event is emitted when an existing binding is removed.
The name of the event - always bind
or unbind
.
The listener function to call when the event is emitted.
The "bind" event is emitted when a new binding is added to the context. The "unbind" event is emitted when an existing binding is removed.
The listener function to call when the event is emitted.
Adds the listener
function to the beginning of the listeners array for the
event named eventName
. No checks are made to see if the listener
has
already been added. Multiple calls passing the same combination of eventName
and listener
will result in the listener
being added, and called, multiple
times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter
, so that calls can be chained.
The name of the event.
The callback function
Adds a one-timelistener
function for the event named eventName
to the beginning of the listeners array. The next time eventName
is triggered, this
listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter
, so that calls can be chained.
The name of the event.
The callback function
Returns a copy of the array of listeners for the event named eventName
,
including any wrappers (such as those created by .once()
).
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
Removes all listeners, or those of the specified eventName
.
It is bad practice to remove listeners added elsewhere in the code,
particularly when the EventEmitter
instance was created by some other
component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter
, so that calls can be chained.
Optional
eventName: string | symbolRemoves the specified listener
from the listener array for the event namedeventName
.
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
removeListener()
will remove, at most, one instance of a listener from the
listener array. If any single listener has been added multiple times to the
listener array for the specified eventName
, then removeListener()
must be
called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the
time of emitting are called in order. This implies that anyremoveListener()
or removeAllListeners()
calls after emitting and before the last listener finishes execution
will not remove them fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
Because listeners are managed using an internal array, calling this will
change the position indices of any listener registered after the listener
being removed. This will not impact the order in which listeners are called,
but it means that any copies of the listener array as returned by
the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
event (as in the example below), removeListener()
will remove the most
recently added instance. In the example the once('ping')
listener is removed:
import { EventEmitter } from 'node:events';
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
Returns a reference to the EventEmitter
, so that calls can be chained.
By default EventEmitter
s will print a warning if more than 10
listeners are
added for a particular event. This is a useful default that helps finding
memory leaks. The emitter.setMaxListeners()
method allows the limit to be
modified for this specific EventEmitter
instance. The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter
, so that calls can be chained.
Protected
setupProtected
setupSet up the configuration resolver if needed
Add a context event observer to the context
Context observer instance or function
Create a plain JSON object for the context
Unbind a binding from the context. No parent contexts will be checked.
Binding key
true if the binding key is found and removed from this context
Remove the context event observer from the context
Context event observer
A debug function which can be overridden by subclasses.