我有一个图像pic.jpeg,我必须在浏览器上显示。这里是我写的代码片段。使用nodejs服务图像
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;
});
});
上面的代码工作的时间和图像的显示器像它应该最,但有时图像丢失。
我很想知道为什么你说“理想情况下”应该使用nginx或类似的代替静态文件的节点。 – 2013-02-18 13:17:35
删除它,只是为了让人们不要太好奇。 :) – 2013-02-18 13:20:35