Dejan Toteff Dejan Toteff - 1 year ago 114
Javascript Question

Better way of exchanging data between two Node.js routes

It would be beneficial, if there is a optimized way of communication between two Node.js routes?
I use mainly Express and I don't know of a Express module, that provides such functionality. I am unsure whether I am missing the right framework or the right NPM script.
I know that this functionality can be implemented via simple Ajax, but I am looking for cleaner solution, such as websockets. I use socket.io, but it seems focused on communication between the client and the server, not between two servers.

Update - What I want to achieve?
Instead of placing all request I need in one file, such as:

router.post('/entode', function(req, res) {
var word_rf = req.body.word1;
if( /^[a-zA-Z]+$/g.test( word_rf ) && word_rf.length<18 ) {
entode.entode_function_rf(word_rf, function (res1) {
io.sockets.emit('series_results', res1);
res.send('done');
});
} else {
io.sockets.emit('error_rf', 'incorrect input');
res.send('done');
}
});
//-------------------------
router.post('/yandex_short', function(req, res) {
var word_rf = req.body.word1;
...
});
//-------------------------
router.post('/yandex_long', function(req, res) {
var word_rf = req.body.word1;
...
});


I prefer having something like:

router.post('/', function(req, res) {
var word_rf = req.body.word1;
var aPromise = new Promise(function(resolve,reject) {
makeRequestFn('./some_route/'+word_rf,function(returnedData){
resolve(returnedData)
});
});
aPromise.then(function(data) {
io.sockets.emit('series_results', data);
res.send('done');
});
//The other routes stay inside this scope
});


In this way I don't need to require the modules, as I transfer the logic directly to other files.

Answer Source

Sorry I am late to the party but I think what you want is inter-process communication. Also instead of reasoning in terms of routes, think in terms of microservices. So what you end up having are decoupled mini apps that can share data between themselves via websocket, message queues, http, etc.

Read this excellent article from the NGINX blog. It is part of a series that will guide you through the process of building your own microservices.

Cheers,

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download