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, "", 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

    3 answers 3

    Pass a callback to the makeRequest that will be called when the connection is closed.

     // ... makeRequest(obj.name, obj.pwd, obj.com, function(answer) { response.write(answer); }) // ... // ... function makeRequest(name, pwd, com, onClose) { // ... client.on('close', function() { onClose(answer) }); } 

    Well, the rest of the code will need to be fixed a little.

    • console.log ('1'); if (pathname == "/ getdata") {if (obj.name! = undefined && obj.pwd! = undefined && obj.com! = undefined) {makeRequest (obj.name, obj.pwd, obj.com, function (ans) {answer = ans.toString ('utf-8', 0, ans.length); console.log ("makerequest answer:" + answer);}); } else {answer = "error in data"; }} else {} console.log ('2'); produces in the console 1,2, "makerequest answer:", and I need 1, "makerequest answer:", 2 - i.e. wait for a response from the socket and only then return it to the client. - deivan_
    • but if you add this call to makeRequest (): response.writeHead (200, {"Content-Type": "text / html", 'Access-Control-Allow-Origin': '*'}); response.write ("<pre>" + answer + "</ pre>"); response.end (); then my task is wonderfully solved !!! .. thanks for the correct target designation! - deivan_

    answer should handle the callback that makeRequest should take in parameters, i.e. something like:

     function makeRequest( bla, bla, bla, callback ) { // ..... client.on('close', function(){ callback( answer ) }) } if( obj.name && obj.pwd && obj.com ) { makeRequest( bla, bla, bla, handleAnswer) } else { handleAnswer( 'error in data' ); } function handlerAnswer( answer ) { // check answer here } 

      That you have nothing EventDriven approach. This is the usual procedural approach, within which you write some crutches.

      The classic Event Driven approach is usually built around a cycle of handling events and exchanging messages / events between procedures and / or objects.

      You do not have a processing cycle or a dispatcher and there is something similar to messages. Recycle the code in the direction of the processing cycle - then everything will become simpler and clearer.

      • one
        The loop itself is hidden under the hood of node.js. Is not it so? - Nofate
      • Barmaley, can you give an example regarding my task? .. - deivan_