cluster-ipc
v1.1.1
Published
Node IPC with unix socket
Downloads
4
Readme
cluster-ipc
A Node IPC module base on Unix socket
Example
cluster mode
'use strict'
const cluster = require('cluster')
const os = require('os');
const path = require('path');
const Messenger = require('ipc-messenger').Messenger
const Mailbox = require('ipc-messenger').Mailbox
const sockPath = path.join(os.tmpdir(), 'ipc-messenger.sock')
if (cluster.isMaster) {
!(async function setup() {
const messenger = new Messenger({ sockPath })
await messenger.init()
const masterBox = new Mailbox({ name: 'master' })
masterBox.send({
to: 'worker2',
data: 'hello',
})
for (let i = 1; i < 5; i++) {
cluster.fork({
env: { BOX_ID: i }
})
}
})().catch(console.error)
} else {
const workerBox = new Mailbox({ name: `worker${process.env.BOX_ID}`})
workerBox.on('request', mail => {
const { to, data, from } = mail
console.log(to) // 'worker2'
console.log(from) // 'master'
console.log(data) // 'hello'
})
}
API
Method
send
send message to another box
const reply = await box1.send({
to: 'box2', // required, target box name support RegExp.
data: { action: 'getPid' }, // optional, custom message.
oneway: false, // optional, no reply? default false.
timeout: 5000, // optional, request timeout, default 5000
})
console.log(reply); // { id: 1, from: 'box2', to: 'box1', isReply: true, data: { pid: 123 } };
reply
reply message to sender
box2.reply({
id: 1, // mail id
to: 'box1',
data: { pid: 123 },
})
broadcast
send message to another boxes
box1.broadcast({
data: 'hi, all',
})
event
request
box1.on('request', payload => {
console.log(payload); // { id: 1, from: 'box2', to: 'box1', data: { 'my box2' } }
})
online
other box online event
box1.on('online', payload => {
console.log(payload); // { id: 1, from: 'box2' }
})
To be perfect