通过http-node.js发送jpg的问题

我试图写一个简单的HTTP Web服务器,(其中包括其他function),可以发送客户端请求的文件。
发送一个普通的文本文件/ HTML文件作为一种魅力。 问题是发送图像文件。
这里是我的代码的一部分(parsingMIMEtypes,并包括fs node.js模块):

if (MIMEtype == "image") { console.log('IMAGE'); fs.readFile(path, "binary", function(err,data) { console.log("Sending to user: "); console.log('read the file!'); response.body = data; response.end(); }); } else { fs.readFile(path, "utf8", function(err,data) { response.body = data ; response.end() ; }); } 

为什么我打开的http://localhost:<serverPort>/test.jpg是空白页面?

下面是关于如何以最简单的方式发送一个带有Node.js的图片的完整示例(我的示例是一个gif文件,但可以与其他文件/图片types一起使用):

 var http = require('http'), fs = require('fs'), util = require('util'), file_path = __dirname + '/web.gif'; // the file is in the same folder with our app // create server on port 4000 http.createServer(function(request, response) { fs.stat(file_path, function(error, stat) { var rs; // We specify the content-type and the content-length headers // important! response.writeHead(200, { 'Content-Type' : 'image/gif', 'Content-Length' : stat.size }); rs = fs.createReadStream(file_path); // pump the file to the response util.pump(rs, response, function(err) { if(err) { throw err; } }); }); }).listen(4000); console.log('Listening on port 4000.'); 

更新:

util.pump已经被弃用了一段时间,你可以使用stream来实现这个:

 fs.createReadStream(filePath).pipe(req);