您所拥有的主要问题是立即
response.end()被致电。您只需在文件完成
response.write调用后调用它。
最简单的方法是使用控制流库。管理多个异步回调通常很复杂。
https://github.com/joyent/node/wiki/modules#wiki-async-
flow
我将使用异步库,因为它是我最了解的一个。
var fs = require('fs');var async = require('async');function css(response) { response.writeHead(200, {"Content-Type": "text/css"}); async.eachSeries( // Pass items to iterate over ['css/bootstrap.css', 'css/bootstrap-responsive.css'], // Pass iterator function that is called for each item function(filename, cb) { fs.readFile(filename, function(err, content) { if (!err) { response.write(content); } // Calling cb makes it go to the next item. cb(err); }); }, // Final callback after each item has been iterated over. function(err) { response.end() } );}如果您想在没有库的情况下完成此工作,或者只是想用另一种方式,这就是我将更直接地做到这一点的方式。基本上,您保留a
count并
end在两个文件读取完成后调用。
function css(response) { response.writeHead(200, {"Content-Type": "text/css"}); var count = 0; var handler = function(error, content){ count++; if (error){ console.log(error); } else{ response.write(content); } if (count == 2) { response.end(); } } fs.readFile('css/bootstrap.css', handler); fs.readFile('css/bootstrap-responsive.css', handler);}


