HTML and CSS Reference
In-Depth Information
this.respond(200, {
message: messages,
token: messages[messages.length - 1].id
});
}.bind(this));
}
14.6.3 Response Headers and Body
The final missing piece of the puzzle is encoding the response data as JSON and
writing the response body. I will leave TDD-ing these features into the respond
method as a last exercise for this chapter. For completeness, Listing 14.79 shows
one possible outcome of the respond method.
Listing 14.79 The respond method
respond: function (status, data) {
var strData = JSON.stringify(data)
||
"{}";
this.response.writeHead(status, {
"Content-Type": "application/json",
"Content-Length": strData.length
});
this.response.write(strData);
this.response.end();
}
And that's it! To take the application for a spin, we can launch another command
line session, as Listing 14.80 shows.
Listing 14.80 Manually testing the finished app from the command line
$ node-repl
node> var msg = { user:"cjno", message:"Enjoying Node.js" };
node> var data = { topic: "message", data: msg };
node> var encoded = encodeURI(JSON.stringify(data));
node> require("fs").writeFileSync("chapp.txt", encoded);
node> Ctrl-d
$ curl -d `cat chapp.txt` http://localhost:8000/comet
$ curl http://localhost:8000/comet
{"message":[{"id":1,"user":"cjno",\
"message":"Enjoying Node.js"}],"token":1}
 
Search WWH ::




Custom Search