How to serve an image using nodejs

前端 未结 11 1432
渐次进展
渐次进展 2020-11-22 08:18

I have a logo that is residing at the public/images/logo.gif. Here is my nodejs code.

http.createServer(function(req, res){
  res.writeHead(200,          


        
11条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 08:56

    I agree with the other posters that eventually, you should use a framework, such as Express.. but first you should also understand how to do something fundamental like this without a library, to really understand what the library abstracts away for you.. The steps are

    1. Parse the incoming HTTP request, to see which path the user is asking for
    2. Add a pathway in conditional statement for the server to respond to
    3. If the image is requested, read the image file from the disk.
    4. Serve the image content-type in a header
    5. Serve the image contents in the body

    The code would look something like this (not tested)

    fs = require('fs');
    http = require('http');
    url = require('url');
    
    
    http.createServer(function(req, res){
      var request = url.parse(req.url, true);
      var action = request.pathname;
    
      if (action == '/logo.gif') {
         var img = fs.readFileSync('./logo.gif');
         res.writeHead(200, {'Content-Type': 'image/gif' });
         res.end(img, 'binary');
      } else { 
         res.writeHead(200, {'Content-Type': 'text/plain' });
         res.end('Hello World \n');
      }
    }).listen(8080, '127.0.0.1');
    

提交回复
热议问题