Andrew
Andrew

Reputation: 43

NodeJS response.write inside callback

I'm using a route to process a url. The functions fire as expected. What I'm trying to do is use the response.write() inside of a call back. I understand this isn't working because the call back doesn't have access to the same variables as the function that calls it, but I'm wondering what the correct NODE way of doing this would be.

route.post('/{type}subject/{method}', function (request,response) {
var post = "";
request.on('data', function (chunk){
    post += chunk;
});
request.on('end', function (){
    postData = qs.parse(post);
    response.writeHead(200);
    switch(request.params['method'].toLowerCase())
    {
        case "registerobserver":
            if (postData['uri']){
                registerObserver (request.params['type'], postData['uri']);
                response.write(success("registerobserver"));
            }
            else
                response.write(failure("1","uri undefined"));

            break;
        case "unregisterobserver":
            if (postData['uri']){
                client.query ('DELETE observers FROM observers INNER JOIN type ON (observers.TypeID = type.TypeID) WHERE observers.uri ="'+postData['uri']+'" AND type.name = "'+request.params['type']+'"', 
                function(err, info) 
                {
                    if(err){
                        response.write(failure("2", "general database failure"));}
                    else{   
                    if(info.affectedRows != 0)
                        response.write(success("unregisterobserver")); //this code does not trigger a response due to namespace

                    else
                        response.write(failure("1", "uri not an observer"));//this code does not trigger a response
                        console.log("uri not observer");
                    }

                    console.log("done");
                })

            }
            else
                response.write(failure("1","uri required"));

            break;
        default:

    }

    response.end();
})
//response.write("type: "+request.params['type']+"<br/>method="+request.params['method']);

});

function success(method){return "<?xml version=\"1.0\"?>\n<response stat=\"ok\">\n\t<method>"+method+"</method>\n</response>";}
function failure(code, message){return "<?xml version=\"1.0\"?>\n<response stat=\"fail\">\n\t<err code=\""+code+"\" msg = \""+message+"\" />\n</response>";}

Upvotes: 2

Views: 6139

Answers (1)

Gil
Gil

Reputation: 3638

Basically what happens is that the async query handler function will be called after your response.end() function call. As such any writes will fail.

You need to call response.end() from inside the callback instead, and take care to not otherwise call response.end() once you are in async code path. Ie. return immediately after the client.query() call.

Upvotes: 8

Related Questions