Background briefing: I wrote the code below to instruct node.js: (1) to assemble an HTML page from three text files in which I stored the pageheader, pagebody, and pagefooter components, respectively. Obviously, these fragments of the page must be assembled in the correct order. On the other hand, there is generally no requirement that these fragments of pages be extracted from their text files in any order before they are assembled. And I want to take advantage of this by implementing parallel asynchrony.
Implementation Code:
var sys = require('sys'),
http = require('http'),
fs = require('fs'),
Q = require('q'),
fullpage, pageheader, pagebody, pagefooter;
fullpage = '';
fs_readheader = fs.readFile('./htmlfiles.1', 'utf-8', function (err, data) {
if (err) { throw err; }
return pageheader = data;
});
fs_readbody = fs.readFile('./htmlfiles.2', 'utf-8', function (err, data) {
if (err) { throw err; }
return pagebody = data;
});
fs_readfooter = fs.readFile('./htmlfiles.3', 'utf-8', function (err, data) {
if (err) { throw err; }
return pagefooter = data;
});
finish = function(err, data) {
if (err) { throw err; }
console.log(pageheader);
data = pageheader + pagebody + pagefooter;
console.log(data);
return fullpage = data;
}();
Q.all([fs_readheader,fs_readbody,fs_readfooter]).then(finish);
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(fullpage);
response.end();
}).listen(8001);
Problem: the node.js server doesnβt display anything at 127.0.0.1:8001 I expected, of course, the full rendering of the HTML page. I am using version 1.00 q.js, which is the latest version of q.js at this point in time.
Aftermath:
- - :
var http = require('http'),
fs = require('fs'),
Q = require('q');
var readFileP = Q.denodeify(fs.readFile);
http.createServer(function(request, response) {
Q.all([ readFileP('./htmlfiles.1', 'utf-8'),
readFileP('./htmlfiles.2', 'utf-8'),
readFileP('./htmlfiles.3', 'utf-8') ])
.done(function(content){
response.writeHead(200, {"Content-Type": "text/html"});
response.end(content.join(''));
});
}).listen(8001);
- , , HTML- - . '' join, , . "done", , - . , , - , "fail" - .