0.0.3 • Published 6 years ago

fork-rx v0.0.3

Weekly downloads
2
License
ISC
Repository
github
Last release
6 years ago

FORK-RX

alt cover

This package will help you communicate with forked processes in NodeJS RX-way. You can send messages and receive them with typed data.

Getting started

First you will need to fork your worker with one simple command:

// parent.ts
import { Worker } from 'fork-rx';

let child = new Worker('Child', '/demo/child.ts');
child.run();

You have to pass name and path to your child JavaScript and TypeScript process. Path calculates from project root. TypeScript worker will work perfectly in ts-node.

To stop process from parent just call:

// parent.ts
child.stop();

Listening to any messages

To get data from child just call listen():

// parent.ts
child.listen().subscribe(x => {
    console.log('parent: ', x);
});

When your child sends you a new message you will receive it as 'x'. It is a structured message with interface IForkMessage.

export interface IForkMessage {
    action: any;
    data: any;
    replyTo?: string;
    to?: string;
}
  • action - action type that you can define in your contracts.
  • data - structured data also defined by your contracts
  • replyTo - if you send message and wait for reply, this property will be generated automatically.
  • to - set replyTo string in this property to reply to a specific message.

Sending messages

To send massages to a child you have two methods:

  • send() - sends message and do not wait for a reply.
// parent.ts
child.send<string>('test', 'string message');
  • sendWithReply() - sends message and listen to a reply only to this massage.
// parent.ts
child.sendWithReply<string>('test', 'string message').subscribe(x => {
    console.log('parentReply: ', x);
});

- is a data interface that you use to communicate with child. It could be any data structure. 'test' - action type. 'string message' - data you want to pass.

Working with child process

Now let's see how we can get message from parent inside child process. In child component you need to import child class.

// child.ts
import { ChildWorker } from 'fork-rx';

let child = new ChildWorker();

listen() method is the same, so let's see, how we swith between different actions and reply:

// child.ts
child.listen().subscribe((post: IForkMessage) => {
    switch (post.action) {
        case 'action1':
            console.log('child get action 1 with data: ', post.data);
            child.send<string>('replyAction', 'data to reply', post.replyTo);
    }
})

Notice that we used 'post.replyTo' to reply to a specific message. Other methods are the same:

  • send() - sends message to a parent and do not wait for a reply.
  • sendWithReply() - sends message and listen to a reply only to this massage.
  • stop() - stop child process.
0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago