Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
The p-event package is a utility for converting event emitters into promises. It allows you to wait for an event to be emitted, making it easier to work with asynchronous event-driven code.
Wait for a single event
This feature allows you to wait for a single event to be emitted. The promise resolves with the event data when the event is emitted.
const pEvent = require('p-event');
const EventEmitter = require('events');
const emitter = new EventEmitter();
(async () => {
const eventData = await pEvent(emitter, 'data');
console.log(eventData); // Logs the data emitted
})();
emitter.emit('data', 'Hello, world!');
Wait for multiple events
This feature allows you to wait for multiple events to be emitted. The promise resolves when all specified events have been emitted.
const pEvent = require('p-event');
const EventEmitter = require('events');
const emitter = new EventEmitter();
(async () => {
const [data1, data2] = await Promise.all([
pEvent(emitter, 'data1'),
pEvent(emitter, 'data2')
]);
console.log(data1, data2); // Logs the data emitted by both events
})();
emitter.emit('data1', 'First event');
emitter.emit('data2', 'Second event');
Timeout for events
This feature allows you to specify a timeout for waiting for an event. If the event is not emitted within the specified time, the promise is rejected.
const pEvent = require('p-event');
const EventEmitter = require('events');
const emitter = new EventEmitter();
(async () => {
try {
const eventData = await pEvent(emitter, 'data', {timeout: 1000});
console.log(eventData);
} catch (error) {
console.error('Event did not occur within 1 second');
}
})();
Filter events
This feature allows you to filter events based on a condition. The promise resolves only when an event that matches the filter condition is emitted.
const pEvent = require('p-event');
const EventEmitter = require('events');
const emitter = new EventEmitter();
(async () => {
const eventData = await pEvent(emitter, 'data', {
filter: data => data === 'specific data'
});
console.log(eventData); // Logs 'specific data'
})();
emitter.emit('data', 'other data');
emitter.emit('data', 'specific data');
The event-to-promise package provides similar functionality by converting event emitters into promises. It allows you to wait for a single event or multiple events, but it does not offer as many advanced features like filtering or timeouts.
The promise-event package is another alternative that converts event emitters into promises. It is simpler and more lightweight compared to p-event, but it lacks some of the advanced features such as filtering and timeouts.
The await-event package allows you to await events in a similar manner to p-event. It provides basic functionality for waiting for events but does not include advanced options like filtering or timeouts.
Promisify an event by waiting for it to be emitted
Useful when you need only one event emission and want to use it with promises or await it in an async function.
It's works with any event API in Node.js and the browser (using a bundler).
If you want multiple individual events as they are emitted, you can use the pEvent.iterator()
method. Observables can be useful too.
$ npm install p-event
In Node.js:
const pEvent = require('p-event');
const emitter = require('./some-event-emitter');
(async () => {
try {
await pEvent(emitter, 'finish');
// `emitter` emitted a `finish` event
console.log(result);
} catch (error) {
// `emitter` emitted an `error` event
console.error(error);
}
})();
In the browser:
const pEvent = require('p-event');
(async () => {
await pEvent(document, 'DOMContentLoaded');
console.log('😎');
})();
Async iteration:
const pEvent = require('p-event');
const emitter = require('./some-event-emitter');
(async () => {
const asyncIterator = pEvent.iterator(emitter, 'data', {
resolutionEvents: ['finish']
});
for await (const event of asyncIterator) {
console.log(event);
}
})();
Returns a Promise
that is fulfilled when emitter
emits an event matching event
, or rejects if emitter
emits any of the events defined in the rejectionEvents
option.
The returned promise has a .cancel()
method, which when called, removes the event listeners and causes the promise to never be settled.
Type: Object
Event emitter object.
Should have either a .on()
/.addListener()
/.addEventListener()
and .off()
/.removeListener()
/.removeEventListener()
method, like the Node.js EventEmitter
and DOM events.
Type: string
Name of the event to listen to.
If the same event is defined both here and in rejectionEvents
, this one takes priority.
Type: Object
Type: string[]
Default: ['error']
Events that will reject the promise.
Type: boolean
Default: false
By default, the promisified function will only return the first argument from the event callback, which works fine for most APIs. This option can be useful for APIs that return multiple arguments in the callback. Turning this on will make it return an array of all arguments from the callback, instead of just the first argument. This also applies to rejections.
Example:
const pEvent = require('p-event');
const emitter = require('./some-event-emitter');
(async () => {
const [foo, bar] = await pEvent(emitter, 'finish', {multiArgs: true});
})();
Type: number
Default: Infinity
Time in milliseconds before timing out.
Type: Function
Filter function for accepting an event.
const pEvent = require('p-event');
const emitter = require('./some-event-emitter');
(async () => {
const result = await pEvent(emitter, '🦄', value => value > 3);
// Do something with first 🦄 event with a value greater than 3
})();
Returns an async iterator that lets you asynchronously iterate over events of event
emitted from emitter
. The iterator ends when emitter
emits an event matching any of the events defined in resolutionEvents
, or rejects if emitter
emits any of the events defined in the rejectionEvents
option.
This method has the same arguments and options as pEvent()
with the addition of the following options:
Type: Object
Type: string[]
Default: []
Events that will end the iterator.
const fs = require('fs');
function getOpenReadStream(file, callback) {
const stream = fs.createReadStream(file);
stream.on('open', () => {
callback(null, stream);
});
stream.on('error', error => {
callback(error);
});
}
getOpenReadStream('unicorn.txt', (error, stream) => {
if (error) {
console.error(error);
return;
}
console.log('File descriptor:', stream.fd);
stream.pipe(process.stdout);
});
const fs = require('fs');
const pEvent = require('p-event');
async function getOpenReadStream(file) {
const stream = fs.createReadStream(file);
await pEvent(stream, 'open');
return stream;
}
(async () => {
const stream = await getOpenReadStream('unicorn.txt');
console.log('File descriptor:', stream.fd);
stream.pipe(process.stdout);
})().catch(console.error);
MIT © Sindre Sorhus
FAQs
Promisify an event by waiting for it to be emitted
The npm package p-event receives a total of 4,199,056 weekly downloads. As such, p-event popularity was classified as popular.
We found that p-event demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.