我有一个图像 pic.jpeg,我必须在浏览器上显示。这是我编写的代码片段。
var mimeTypes = {
'.js' : 'text/javascript',
'.css' : 'text/css',
'.gif' : 'image/gif',
'.jpeg': 'image/jpeg',
'.html': 'text/html'
};
contenttype = mimeTypes[path.extname(req.url)];
pathname = "." + req.url;
var stream = fs.createReadStream(pathname);
stream.on('error', function(error) {
res.writeHead(500);
res.end();
return;
});
res.setHeader('Content-Type', contenttype);
res.writeHead(200);
stream.on('open', function () {
// This just pipes the read stream to the response object (which goes to the client)
util.pump(stream, res, function(error) {
//Only called when the res is closed or an error occurs
console.log("Error:");
res.end();
return;
});
});
上面的代码在大多数情况下都可以正常工作,并且图像会按原样显示,但有时图像会丢失。