Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

78
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!