How to write this code using non-blocking functions?
var http = require("http");
var url = require("url");
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
if (typeof rh[pathname] === 'function') {
rh[pathname](request, response);
} else {
response.writeHead(404);
response.end();
}}
http.createServer(onRequest).listen(8888);
//Request Handlers
var root = function(request, response) { … }
var hello = function(request, response) {
response.writeHead(200,
{"Content-Type": "text/html"});
response.write("…"); //body
response.end();}
//Routing Table (Map URL -> Request Handler)
rh["/"] = root;
rh["/hello"] = hello;
request.url
request.method
request.headers
var url = require(‘url’);
var p_url = url.parse('/status?name=cp', true);
p_url = {
href: '/status?name=cp',
search: '?name=cp',
query: { name: ‘cp' },
pathname: '/status'
}
response.writeHead(statusCode, [msg], [headers]);
response.write(body);
response.end();
Explicit Headers
response.setHeader(key, value);
response.getHeader(key);
response.statusCode
response.write(body);
response.end();
Implicit Headers
//blocking function
function(arguments)
var y = f(x);
...
Blocking functions return their result when they finish
//non-blocking function
function(arguments, callback)
f(x, function(y) { ... });
Non-blocking functions return immediately and use callbacks to pass the results
var y = f(x);
var z = g(y);
var z = g(f(x));
...
How to write this code using non-blocking functions?
Request Events
var postData = "";
request.setEncoding("utf8");
request.on("data",
function(chunk) { postData += chunk; });
request.on("end",
function() {
console.log ("received" + postData);
});
Use a spacebar or arrow keys to navigate