You are viewing a single comment's thread from:

RE: Musing Posts

in #musing-threads6 years ago

In a node.js application, can I call a function from a program running on another server?

I have a site built with node.js. I've also written another node.js application that will send a discord message upon a particular action in the site. I want to run the second application on a different server. Is there a way to call a function from the second server from the site?

Sort:  

You cannot execute a function from a remote server like you'd do from your own server.

But you can expose an API endpoint from the other server and post requests from your current server to that endpoint to do something with the data or request and get back to your current server with result. This is the standard way of doing want you want.

Thanks, time to google my way through that.

You can setup a REST layer to POST to another server that dispatch the discord message. Alternatively, you can use discord.js in the node server that runs your website and send message upon the command called.

The answers seem right to me, however I would also add that if the function you wish to call is stateless, or you can duplicate the state that is necessary to fulfill the functions of that call, then you can simply include the code in both places and call it. If that makes sense. Just be careful, because if the call has side effects that your first server needs to be aware of, you may need to coordinate a bit.

what you refer to is more generally known as a remote procedure call.
https://en.wikipedia.org/wiki/Remote_procedure_call

if you google for "rpc node" you will find some libraries that people have built, but the one I recommend is gRPC because it's backed by google and has good cross language support. Others might recommend apache thrift but I haven't used it. the other suggestion of expose an API endpoint is also a valid way to do this, but the code at the end does not look as clean.

Remote procedure call
In distributed computing, a remote procedure call (RPC) is when a computer program causes a procedure (subroutine) to execute in a different address space (commonly on another computer on a shared network), which is coded as if it were a normal (local) procedure call, without the programmer explicitly coding the details for the remote interaction. That is, the programmer writes essentially the same code whether the subroutine is local to the executing program, or remote. This is a form of client–server interaction (caller is client, executor is server), typically implemented via a request–response message-passing system. In the object-oriented programming paradigm, RPC calls are represented by remote method invocation (RMI).