The problem is [visibilty of object inside and asynchronous calls to functions] of exported model.
exports.send = function(socket, req, callback) {
req.external_response = {}; // initialize empty object
client.connect(socket.Port, socket.IPAddress, function() {
client.write(req.query);
});
client.on('data', function(data, req) {
req.external_response = data.toString('utf8');// assign response to it
// console.log(req.external_response); gives out response
});
client.on('close', function() {
client.destroy();
callback();
});
};
after send finishes and callback is executed i still have
req.external_response = {}
if I do
var tmp = "";
client.on('data', function(data) {
tmp = data.toString('utf8');// assign response to it
// console.log(tmp); gives out
});
req.external_response = tmp; // tmp 'undefined'
I tried various ways to get that data written into variable but no success so far, maybe there is something that I did not noticed/missed. any suggestions how can I write TCP response to a desired variable?
The first snippet doesn't work probably because of variables conflict:
exports.send = function(socket, req, callback) {
req.external_response = {};
client.on('data', function(data, req2) { // <----- req2 !!!
req.external_response = ...
});
client.on('close', function() {
console.log(req.external_response);
client.destroy();
callback();
});
};
The second snippet:
var tmp = "";
client.on('data', function(data) {
tmp = data.toString('utf8');// assign response to it
// console.log(tmp); gives out
});
req.external_response = tmp;
won't work because you assign tmp to req.external_response before the callback assigns data to it.
Here are what I tried to reach what I want: (no result in all of'em)
var assignData = function(source, destination){
destination = source.toString('utf8');
callback();
};
client.on('data', function(data) {
assignData(data,req.external_response);
});
client.on('data', function(data) {
req.external_response = data.toString('utf8');
callback();
});
call to .send(socket, req, callback)
var req = {query:'0000000082&ServiceID=2355&QueryCode=8080'};
sender.send(req, {}, done);