Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

76
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda