Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

NodeJS response.write inside callback

NodeJS response.write inside callback

Problem

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']+"
method="+request.params['method']); }); function success(method){return "\n\n\t"+method+"\n";} function failure(code, message){return "\n\n\t\n";}
Problem courtesy of: Andrew

Solution

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.

Solution courtesy of: Gil

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

NodeJS response.write inside callback

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×