Search code examples
node.jsapiserverrequiremodule.exports

NodeJS is running one script into another one


I created a TCP server for receiving information from some devices, and I wanted to created an API out from this server, and I exported two variables in order to use them in the API. When I do that, my server starts in my other process, making that they execute at the same time, I don't know why this happens

//server.js

const { title, BL_url, puerto_controladores, puerto_api } = require('...')
process.title = title;

var net = require('net');

var sockets = []; 
var socketsID = [];
var lastConnected = [];


var server = net.createServer( function (socket) {

    socket.name = socket.remoteAddress + ":" + socket.remotePort;

    sockets.push(socket);
    socketsID.push(socket.name.substr(7));

    console.log(socket.name + ' connected.');

    socket.on('data', (data) => {
        textChunk = data.toString('utf8').substr(1,data.toString('utf8').length-2);
        console.log('Mensaje de ' + socket.name.substr(7) + 
    socket.on('close', () =>{
        console.log(socket.name + " desconectado.");
    });
    socket.on('error', (error) =>{
        console.log('Error del Cliente TCP: ' + puerto_controladores, error.code, error.message);
    });
    
});

server.on('error', (error) => {
    console.log('Error del Server TCP: ' + puerto_controladores, error.message);
});

server.listen(puerto_controladores, ()=>{
    setInterval(() => {
        webMethods.sendInterval();
    }, 180000);

    
    console.log("Server listening at : " + puerto_controladores);
});
//setInterval(()=>{
    module.exports = {sockets,socketsID};

On the other hand:

const {sockets,socketsID} = require('..server.js');
const {titleProcess,port} = require('...');
process.title = titleProcess;
const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.listen(port, () => {
    console.log('Listening at :',port);
});

app.get('/',(req,res)=>{
    console.log(test.sockets,test.socketsID);
    res.status(200).json({
        mensaje: 'received',

    })
})

Whatever I do in the server.js, a print of module.export, a new variable, including the title of process in command prompt etc. it runs in the API.js console

//API Output: 
Server listening at : 9006
Listening at : 4002
{ sockets: [], socketsID: [] }
{ sockets: [], socketsID: [] }

//Server Output:
Error del Server TCP: 9006 listen EADDRINUSE: address already in use :::9006

Solution

  • Well socket objects in nodejs belong to a particular process. You can't just share them with another process easily. If you want one process to cause data to be sent on a socket the other process owns, then send the data itself to the other process using a different server and send some identifier with the data that the receiving process can use to figure out which socket the data should be sent to and it will then send the data over the socket it has. But, this whole thing sounds like a really confusing way to do things.

    For example, let's say you have serverTCP (the plain TCP server from your server.js) and serverAPI (an Express server from your other file) each in separate processes. Put a separate Express server in serverTCP running on a local port, not open to the outside world. When serverAPI receives some data for some socketID, it then makes an http request to serverTCP and sends the data and the socketID. serverTCP receives that http request, gets the socketID and the data out of that request and sends it out over the appropriate socket it has a connection to.

    FYI, this is generically known as a proxy where your API is somewhat serving as a proxy for the real socket connection. There are all sorts of modules in NPM that implement actual proxies too.