Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

74
Vistas
How to pass data from net.Socket.on to an outside variable or return it

I'm working with net in node.js and I'm sending packet to a server and listening to the response, but I can't manage to return it. Here's my code:

function packetsend (sockeT, packeT) {
    var resp = null;
    if(sockeT) {
         sockeT.write(packeT);
         sockeT.on('data', (data) => {
              resp = data.toString()
         })
    }
    return resp;
}

const socket = new net.Socket();
socket.connect({host: server, port: port}, function() {
    console.log('Connected');
    var packetRecv = packetsend(socket, 'some packet');

    if (packetRecv === 'some') {
        console.log("ok");
    }
})

I don't understand why packetsend() function is not returning the updated resp variable, and sends undefined object instead. When I do console.log(data) inside the sockeT.on() I see that it receives data.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Try transforming your packetsend() function in an async function. Maybe it's not returning the resp because you return it before the event 'data' is invoked.

This is just an example of a possible implementation:

function packetsend (sockeT, packeT) {
    return new Promise((resolve, reject) => {
        if (sockeT) {
            sockeT.write(packeT);
            sockeT.on('data', (data) => {
                resolve(data.toString());
            });

            //WARNING: I don't know this 'socketT' object, don't know if there is an 'error' event.
            //but it's recommended to handle errors. This is just an example.
            sockeT.on('error', (error) => {
                reject(error);
            });
        }
        else{
            reject('Missing sockeT');
        }
    });
}

const socket = new net.Socket();
socket.connect({ host: server, port: port }, function () {
    console.log('Connected');
    packetsend(socket, 'some packet').then(packetRecv => {

        console.log('Received data => '+ packetRecv);

        if (packetRecv === 'some') {
            console.log("ok");
        }
    
    }).catch(error => console.log(error));

})

Update: you can also use the async/await

const socket = new net.Socket();
socket.connect({ host: server, port: port }, async function () {
    try {
        console.log('Connected');
        let packetRecv = await packetsend(socket, 'some packet');
    
        console.log('Received data => '+ packetRecv);
    
        if (packetRecv === 'some') {
            console.log("ok");
        }    
    }
    catch (error) {
        console.log(error);
    }
});

Tips:

  • "promise" documentation
  • "eventEmitter" documentation
  • "async/await" documentation
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda