How to start multiple node.js servers

I have two Express servers running on different ports. The first server (web server) provides a website, and the second server (data server) emits data every 100 ms using socket.io. When I open the website in a browser, the data is displayed as expected. But when I open the website in the second browser, all the emitted data in the first browser slows down noticeably until the second browser loads the site.

I should probably mention that the application runs on Raspberry Pi. Website loading time is not so critical, but data emission.

Is there a way to start node.js servers so that they do not suffer from load on each other?

Now the web server is located in the main app.js file, which is executed by node, and the data server is the module required by the web server. Something like that:

app.js:

var express = require('express');
var data = require('data-server.js');

var app = express();

// Web server setup and handling (mostly Express defaults)

app.listen(3000);

module.exports = app;

server.js data:

var app = require('express')();
var server = require('http').Server(app).listen(3001)
var io = require('socket.io')(server);

// Socket.io code that emits data every 100 ms

module.exports = io;

Update

It turns out that this is my query on the database that was holding on to the node, so it could not emit because the emission function expected the database to be free.

+4
source share
1 answer

You must use the same port and the same node process for both regular HTTP traffic and your Internet traffic. This will minimize the impact of performance on your raspberry pi. Example:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});
+4
source

All Articles