I need to log to a file (I'm currently using winston) every time a socket is closed and it has triggered the 'data' event. Here is my code:
net.createServer(function (socket)
{
var remoteAdressPort = socket.remoteAddress + " - " + socket.remotePort;
socket.on('data', function (data)
{
[...] // some treatments
});
socket.on('close', function() {
logger.info("Socket has been closed : " + remoteAdressPort);
});
}).listen(port);
The problem is that when I listen on the port in question, a lot of sockets that never triggered the 'data' event (and that I'm not interested in) are closed too, which gives me a huge log overload that is not usable. I only want to log the closing of the socket that triggered the 'data' event. Is this possible?
Yeah! You could just keep a variable a scope above your event listener's (e.g. sentData
) and mutate it to true
when the data event comes through, which you can then check in the close
event.
net.createServer(function (socket)
{
let sentData = false;
var remoteAdressPort = socket.remoteAddress + " - " + socket.remotePort;
socket.on('data', function (data)
{
sentData = true;
[...] // some treatments
});
socket.on('close', function() {
if (sentData) {
logger.info("Socket has been closed : " + remoteAdressPort);
}
});
}).listen(port);