Skip to content

Commit

Permalink
chore: add child-process example
Browse files Browse the repository at this point in the history
  • Loading branch information
ulivz committed Nov 16, 2023
1 parent 585b75a commit aafb655
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
21 changes: 21 additions & 0 deletions examples/child-process/channel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { UnPort } from '../../src';

export type ChildProcessChannel = {
parent2child: {
syn: {
pid: string;
};
body: {
name: string;
path: string;
}
};
child2parent: {
ack: {
pid: string;
};
};
};

export type ChildPort = UnPort<ChildProcessChannel, 'child2parent'>;
export type ParentPort = UnPort<ChildProcessChannel, 'parent2child'>;
28 changes: 28 additions & 0 deletions examples/child-process/child.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { defineIntermediatePort, UnPort } from '../../src';
import { ChildPort } from './channel';

// 1. Initialize a port
const port: ChildPort = new UnPort();

// 2. Implement a intermediate port based on underlying IPC capabilities
port.implement(() => {
const intermediatePort = defineIntermediatePort({
postMessage: message => {
process.send && process.send(JSON.stringify(message));
},
});

process.on('message', (message: string) => {
intermediatePort.onmessage && intermediatePort.onmessage(JSON.parse(message));
});
return intermediatePort;
});

// 3. Post message
port.onMessage('syn', payload => {
console.log('[child] [syn]', payload.pid);
port.postMessage('ack', { pid: 'child' });
});
port.onMessage('body', payload => {
console.log('[child] [body]', JSON.stringify(payload.name));
});
31 changes: 31 additions & 0 deletions examples/child-process/parent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { fork } from 'child_process';
import { defineIntermediatePort, UnPort } from '../../src';
import { ParentPort } from './channel';

// 1. Initialize a port
const port: ParentPort = new UnPort();

// 2. Implement a universal port based on underlying IPC capabilities
port.implement(() => {
const childProcess: import('child_process').ChildProcess = fork('./child');
const intermediatePort = defineIntermediatePort({
postMessage: message => {
childProcess.send(JSON.stringify(message));
},
});

childProcess.on('message', (message: string) => {
intermediatePort.onmessage && intermediatePort.onmessage(JSON.parse(message));
});

return intermediatePort;
});

// 3. Post message
port.postMessage('syn', { pid: 'parent' });
port.onMessage('ack', p => {
port.postMessage('body', {
name: 'index',
path: ' /',
});
});

0 comments on commit aafb655

Please sign in to comment.