https://github.com/holepunchto/librpc ABI compatible RPC for Bare.
npm i bare-rpc
import RPC from 'bare-rpc'
// On one end
const rpc = new RPC(stream, (req) => {
if (req.command === 42) {
console.log(req.data.toString()) // ping
req.reply('pong')
}
})
// On the other end
const req = rpc.request(42)
req.send('ping')
const replyBuffer = await req.reply()
console.log(replyBuffer.toString()) // pongCreate an RPC instance using a duplex stream. onrequest is an optional callback run when a remote request is received. This is where processing and responding to an RPC request happens. onrequest receives a RPCIncomingRequest as an argument, for example:
const rpc = new RPC(stream, (req) => {
if (req.command === 42) {
req.reply('pong')
}
})See RPCIncomingRequest for properties and methods for processing the request.
onrequest can also be a RPCCommandRouter.
Create a request for command. command is a unique number that should be used to differentiate different requests on the remote end. Returns a RPCOutgoingRequest.
The command that the request was created with. A command is a unique number.
A boolean for whether the request has been sent.
A boolean for whether the request has received a reply.
Send the request with the provided data. data can be a buffer or a string which will be encoded using encoding.
.send() can only be called once per request.
Await the reply from the remote end to the request. encoding can be defined for decoding the response data buffer back into a string.
Create a Writable stream for sending data with the request.
Create a Readable stream for receiving data in reply to the request.
The command that the request was sent as. A command is a unique number.
The data buffer sent with the request.
A boolean for whether a reply has been sent.
A boolean for whether the request has been received as a stream. See req.createRequestStream() for receiving requests as a stream.
Reply to the request with the provided data. data can be a buffer or a string which will be encoded using encoding.
Create a Readable stream for receiving data from the request.
Create a Writable stream for sending data in reply to the request.
An alternative way to define commands and handlers for receiving them.
Create a new command router. This router can then be used when creating an rpc. For example:
const router = new RPC.CommandRouter()
router.respond(42, (req, data) => {
console.log(data.toString()) // ping
return Buffer.from('pong')
})
const rpc = new RPC(stream, router)
const req = rpc.request(42)
req.send('ping')Define a command and the handler for it. The callback for a command receives both the request (req) and the data buffer and can return a value to respond. If the request is responded to in the callback, the return value is ignored.
Options include:
options = {
// Encoding for incoming request
requestEncoding: c.raw,
// Encoding for outgoing response
responseEncoding: c.raw
}Apache-2.0