2013-02-18 49 views
0

我有一个图像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; 
       }); 
      }); 

上面的代码工作的时间和图像的显示器像它应该最,但有时图像丢失。

回答

2

你不应该通过node.js来提供静态文件。你应该考虑使用Nginx或类似的Web服务器。

或者,您可以使用connect模块为静态文件

var server = connect() 
    .use('/static', connect.static(__dirname + '/static')) 
    .use(router) 
    .listen(port); 

制作名为static一个新的目录,并把所有的文件在里面,这样你就可以通过/static/images/testimage.jpg

+0

我很想知道为什么你说“理想情况下”应该使用nginx或类似的代替静态文件的节点。 – 2013-02-18 13:17:35

+0

删除它,只是为了让人们不要太好奇。 :) – 2013-02-18 13:20:35

0

而不是自己实现静态文件服务,为什么不使用Express之类的库?你可以看到在这里使用:Express Static nodejs或在这里看到API:http://expressjs.com/api.html(搜索“静态”)。它会少得多的代码,并且可靠。

+1

访问它们是我可以做到这一点,但这仅仅是为了教育目的。我想知道事情是如何工作的。 – 2013-02-18 13:13:30