rpc-stream

In notebook:
FrontEndMasters Networking and Streams
Created at:
2017-10-01
Updated:
2017-10-01
Tags:
backend Node JS JavaScript

rpc-stream

The readme of rpc-stream is an excellent source on why you need to make your interfaces as general as possible.

call methods defined by a remote endpoint and you pack it in a stream

It works with methods (see below) and methods have callbacks to inform the remote and that everything is OK.


rpc-stream: server.js

Server example. If a client calls this server, that understands the rpc protocoll, then, it can call the hello method. The server will respond with prepending a string.

var net = require('net')
var rpc = require('rpc-stream')

net.createServer(function (stream) {
  // stream is a duplex stream A.pipe(B).pipe(A)
  stream.pipe(rpc({
    hello: function (name, cb) {
      cb(null, 'howdy ' + name)
    }
  })).pipe(stream)
}).listen(5000)

rpc-stream: client.js

And the client to use this ↴

var net = require('net')
var rpc = require('rpc-stream')

var client = rpc()
// again a duplex stream 
client.pipe(net.connect(5000, 'localhost')).pipe(client)
var remote = client.wrap(['hello'])

remote.hello(process.env.USER, function (err, msg) {
  if (err) return console.error(err)
  console.log(msg)
  client.end()
})

This module is useful, when you just want to quickly expose some methods.