Quickstart
Getting started with p2pbus is quick and easy. Just follow the steps below and you'll be up and running in no time.
Prerequisites
- Node.js version 22 or higher.
Installation
You can install @nhtio/p2pbus directly from your preferred package manager
sh
npm i @nhtio/p2pbussh
pnpm add @nhtio/p2pbussh
yarn add @nhtio/p2pbusInitializing the connection
Create a bus instance
typescript
import { P2PBus } from '@nhtio/p2pbus'
const bus = new P2PBus()Subscribe to events
P2PBus extends the NodeJS Event Emitter, so you can use the same method (i.e.addListener, on), to subscribe to events.
typescript
bus.on('some event', (somePayload: any) => {
...
})You can subscribe to events even before the P2PBus is booted.
Type-Safe Events
You can define the events which you are going to publish and subscribe to by augmenting the EventCallbacks interface.
typescript
declare module '@nhtio/p2pbus' {
interface EventCallbacks {
'test-event': (arg: string) => void
}
}Boot the P2P Service
Start the P2P service by calling P2PBus.boot
typescript
await bus.boot()Publishing an Event
While the emit method exists on the P2PBus, it is only used for local events and shouldn't be used. Instead, you can use P2PBus.publish much the same way that you would use emit:
typescript
await bus.publish('some-event', 'some-string', {}, true, null, 'foo')