Home NodeJS - syncronize two listeners
Reply: 1

NodeJS - syncronize two listeners

user3144605 Published in 2018-01-12 17:53:00Z

I have a Node.JS server that listens on two ports. The standard HTTP is on port 3000 and it provides an API with two routes: /getInfo and /sendCommand. I have another listener on 3001 for a specific protocol, where a device is connected. The goal is to execute an API call from the web interface and send it to the device in order to receive the output. Something like:

GET localhost:3000/getInfo
server sends command to the device connected on localhost:3001
server receives some output
server responses to the request

How should the code look like since Node.JS requests and responses are asynchronous with the other server?

Server for devices:

var raspberryList = [];

function sendCommand(name, command) {
    for (var i = 0; i < raspberryList.length; i++) {
        if (!raspberryList[i].name.localeCompare(name)) {

var server = net.createServer(function(socket) {
    socket.name = socket.remoteAddress;
    console.log(socket.name + " joined.";

    socket.on('data', function(data) {
        // TODO: Data received here should be displayed into the web interface
        console.log(socket.name + " > " + data);

    socket.on('end', function() {
        raspberryList.splice(raspberryList.indexOf(socket), 1);
        console.log(socket.name + " left.");


Node.JS API route:

app.post('/getInfo', function(req, res) {
    // TODO: send the command somehow and get the output

    // Send the response
Tudor Reply to 2018-01-12 22:20:10Z

If you are using HTTP on port 3001 you can try using request.

var request = require('request');
app.post('/getInfo', function(req, res) {

request('http://localhost:3000/endpoint', function (error, response, body) {

if (error) throw error;

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.303114 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO