I try for my project to transfer the server part to use node.js. There was a task that I can’t solve - I don’t understand the logic of the structure that needs to be built. Details in the code:
var httpServer = http.createServer(function (request, response) { var parseUrl=url.parse(request.url,true), pathname = parseUrl.pathname, obj=parseUrl.query; //console.log(parseUrl.query); var answer="ERROR"; if(pathname=="/getdata") { if(obj.name != undefined && obj.pwd != undefined && obj.com != undefined) { answer=makeRequest(obj.name,obj.pwd,obj.com); } else { answer="error in data"; } } else { } response.writeHead(200, {"Content-Type": "text/html", 'Access-Control-Allow-Origin' : '*'}); response.write(answer); response.end(); });
here, the server processes the client request, but to respond to it, the server needs to send data to another server's socket, retrieve the data and return it to return to the client. from makeRequest (...) I want to get an answer from the socket, the communication with which for the time being is implemented like this:
function makeRequest(name,pwd,com) { var client = new net.Socket(),answer=[],flag=0; client.connect(3201, "127.0.0.1", function() { client.write('auth "'+name+'" "'+pwd+'"\n'); }); client.on('data', function(data) { answer.push(data); if(data=='_bye') client.destroy(); }); client.write(com+'\n'); client.on('close', function() { return answer; // вот это работать не будет. а мне нужно при закрытии сокетного // соединения вернуть последний ответ в функцию, которая вызвала // этот makeRequest(), т.е. как-то обернуть или замкнуть... }); }
Please help me correctly create such a construction - the return of data from the socket, which in turn should return the answer to the request to the node.js server