Internal
Optional
[SIGNAL]Bail out on the first failed test point
Numeric identifier for this test
Optional
cwdMethod that writes to stderr when debug: true
is set in the options,
or no-ops otherwise
number of spaces to indent the TAP stream
Nesting level, for serialization to node test runner
Note that this is zero for parent-less tests, and also zero for the first level of children.
Do not emit the TAP version 14
line at the start
Options provided to this test
Do not elide extraneous whitespace and empty lines.
true if the stream can be read
Set upon test completion when a child test is ready to be processed by its parent.
True if this test should be buffered and only emit data if it fails
Treat non-TAP data as an error.
May be set with pragma +strict
in the TAP stream, or unset with
pragma: -strict
.
Set to true when the test times out, so its failure status can be determined later.
true if the stream can be written
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
captureValue: boolean
Change the default captureRejections
option on all new EventEmitter
objects.
Static
defaultBy default, a maximum of 10
listeners can be registered for any single
event. This limit can be changed for individual EventEmitter
instances
using the emitter.setMaxListeners(n)
method. To change the default
for allEventEmitter
instances, the events.defaultMaxListeners
property
can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
change affects all EventEmitter
instances, including those created before
the change is made. However, calling emitter.setMaxListeners(n)
still has
precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
more listeners to be added but will output a trace warning to stderr indicating
that a "possible EventEmitter memory leak" has been detected. For any single
EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
The --trace-warnings
command-line flag can be used to display the
stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
have the additional emitter
, type
, and count
properties, referring to
the event emitter instance, the event's name and the number of attached
listeners, respectively.
Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
regular 'error'
listener is installed.
True if the stream has been aborted.
No-op setter. Stream aborted status is set via the AbortSignal provided in the constructor options.
true if this is an async stream
Set to true to make this stream async.
Once set, it cannot be unset, as this would potentially cause incorrect behavior. Ie, a sync stream can be made async, but an async stream cannot be safely made sync.
The amount of data stored in the buffer waiting to be read.
For Buffer strings, this will be the total byte length.
For string encoding streams, this will be the string character length,
according to JavaScript's string.length
logic.
For objectMode streams, this is a count of the items waiting to be
emitted.
true if the stream has been forcibly destroyed
true if the 'end' event has been emitted
The BufferEncoding
currently in use, or null
true if the stream is currently in a flowing state, meaning that any writes will be immediately emitted.
True if this is an objectMode stream
true if the stream is currently in a paused state
Boolean indicating whether the underlying stream can be written to, or if it has been ended.
Static
isAlias for isStream
Former export location, maintained for backwards compatibility.
Optional
[captureRest
...args: AnyRestAlias for Minipass#on
Rest
...args: TapFileEvents[Event]Destroy a stream, preventing it from being used for any further purpose.
If the stream has a close()
method, then it will be called on
destruction.
After destruction, any attempt to write data, read data, or emit most events will be ignored.
If an error argument is provided, then it will be emitted in an 'error' event.
Optional
er: unknownMark the test as ended. In this base class, this is a no-op, but in @tapjs/core!test-base.TestBase, it also triggers the other end-of-test operations.
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) ]
Returns the current max listener value for the EventEmitter
which is either
set by emitter.setMaxListeners(n)
or defaults to defaultMaxListeners.
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] ]
Mostly identical to EventEmitter.off
If a 'data' event handler is removed, and it was the last consumer (ie, there are no pipe destinations or other 'data' event listeners), then the flow of data will stop until there is another consumer or Minipass#resume is explicitly called.
Rest
...args: TapFileEvents[Event]Mostly identical to EventEmitter.on
, with the following
behavior differences to prevent data loss and unnecessary hangs:
Adding a 'data' event handler will trigger the flow of data
Adding a 'readable' event handler when there is data waiting to be read will cause 'readable' to be emitted immediately.
Adding an 'endish' event handler ('end', 'finish', etc.) which has already passed will cause the event to be emitted immediately and all handlers removed.
Adding an 'error' event handler after an error has been emitted will cause the event to be re-emitted immediately with the error previously raised.
Rest
...args: TapFileEvents[Event]Method called when the parser encounters a bail out
Extended by @tapjs/core!test-base.TestBase
Optional
reason: stringAdds a one-time listener
function for the event named eventName
. The
next time eventName
is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter
, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener()
method can be used as an alternative to add the
event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The name of the event.
The callback function
Rest
...args: any[]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
Rest
...args: any[]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
Rest
...args: any[]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');
Low-level explicit read method.
In objectMode, the argument is ignored, and one item is returned if available.
n
is the number of bytes (or in the case of encoding streams,
characters) to consume. If n
is not provided, then the entire buffer
is returned, or null
is returned if no data is available.
If n
is greater that the amount of data in the internal buffer,
then null
is returned.
Optional
n: null | numberMostly identical to EventEmitter.removeAllListeners
If all 'data' event handlers are removed, and they were the last consumer (ie, there are no pipe destinations), then the flow of data will stop until there is another consumer or Minipass#resume is explicitly called.
Optional
ev: EventAlias for Minipass#off
Rest
...args: TapFileEvents[Event]Resume the stream if it is currently in a paused state
If called when there are no pipe destinations or data
event listeners,
this will place the stream in a "discarded" state, where all data will
be thrown away. The discarded state is removed if a pipe destination or
data handler is added, if pause() is called, or if any synchronous or
asynchronous iteration is started.
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 to Infinity
(or 0
) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter
, so that calls can be chained.
Fully unhook a piped destination stream.
If the destination stream was the only consumer of this stream (ie,
there are no other piped destinations or 'data'
event listeners)
then the flow of data will stop until there is another consumer or
Minipass#resume is explicitly called.
Static
addExperimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
lead to resource leaks since another third party with the signal can
call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
this since it would violate the web standard. Additionally, the original
API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
two issues by listening to the event such that stopImmediatePropagation
does
not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
Disposable that removes the abort
listener.
Static
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
the emitter.
For EventTarget
s this is the only way to get the event listeners for the
event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
Static
getReturns the currently set max amount of listeners.
For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
event target. If the number of event handlers on a single EventTarget exceeds
the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
Static
getStatic
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
The emitter to query
The event name
Static
onimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
Returns an AsyncIterator
that iterates eventName
events. It will throw
if the EventEmitter
emits 'error'
. It removes all listeners when
exiting the loop. The value
returned by each iteration is an array
composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
Optional
options: StaticEventEmitterIteratorOptionsAn AsyncIterator
that iterates eventName
events emitted by the emitter
Optional
options: StaticEventEmitterIteratorOptionsStatic
onceCreates a Promise
that is fulfilled when the EventEmitter
emits the given
event or that is rejected if the EventEmitter
emits 'error'
while waiting.
The Promise
will resolve with an array of all the arguments emitted to the
given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
'error'
event itself, then it is treated as any other kind of event without
special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]Internal
bufferedTrue if this test should be buffered and only processed on completion
Optional
deferredA Deferred
promise wrapper that is resolved when this test completes.
TapWrap AsyncResource that limits the async-hook-domain
the async-hook-domain that catches throws and Promise rejections
Internal
outputthe TAP stream data for buffered tests
Optional
parentParent test of this TAP stream
The tap parser attached to this TAP stream
high resolution bigint time when this test started
Optional
timerThe timer that fires when the test times out
Internal
EventEmitter emit method, but closes the
@tapjs/core!base.Base#hook and
@tapjs/core!base.Base#hookDomain when emitting 'end'
.
Rest
...data: TapFileEvents[Event]Internal
Method called when the parser completes and emits its final results
Extended by @tapjs/core!worker.Worker and @tapjs/core!tap.TAP classes
Internal
Run the main
test function. Called by
@tapjs/core!test-base.TestBase when starting a subtest.
Initializes the TapWrap hook
Internal
Called when a timeout occurs. Only exposed because it has to be called and/or extended by other classes, which all have their own sorts of timeout behavior specific to the type of thing they represent.
Optional
expired?: stringOptional
message?: stringInternal
Stream write method.
For buffered tests, this collects the output in the
@tapjs/core!base.Base#output
field. Sets @tapjs/core!base.Base#printedOutput to true
when
called.
Note: you probably never need to call this. Instead, use the various assertion methods and other parts of the API.
Set the amount of time in milliseconds before this test is considered
a timeout. The time is counted from right now, so for example, repeatedly
calling t.setTimeout(100)
can keep it going indefinitely, as long as
you call it more often than every 100ms.
Calling setTimeout(0)
will remove the timer and allow the test to run
indefinitely.
True if this test emitted a bailout
The count of all assertions that this stream emitted
Unrecoverable TAP protocol errors in the stream
High resolution time in ns that this test took to complete.
Lists of todo, skip, and failure test points. If passes: true
is
set in the options, then passing test points will also be tracked.
the name of this test
Optional
resultsSet on completion. The results of the test run.
Amount of time in milliseconds that this test took to complete.
True if the test has printed some output of any kind
Returns true if this test has begun
Class representing standard input as a TAP stream
Instantiated by
t.stdin()
, typically.