How to serve an image using nodejs

前端 未结 11 1266
渐次进展
渐次进展 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 09:00

    Vanilla node version as requested:

    var http = require('http');
    var url = require('url');
    var path = require('path');
    var fs = require('fs');
    
    http.createServer(function(req, res) {
      // parse url
      var request = url.parse(req.url, true);
      var action = request.pathname;
      // disallow non get requests
      if (req.method !== 'GET') {
        res.writeHead(405, {'Content-Type': 'text/plain' });
        res.end('405 Method Not Allowed');
        return;
      }
      // routes
      if (action === '/') {
        res.writeHead(200, {'Content-Type': 'text/plain' });
        res.end('Hello World \n');
        return;
      }
      // static (note not safe, use a module for anything serious)
      var filePath = path.join(__dirname, action).split('%20').join(' ');
      fs.exists(filePath, function (exists) {
        if (!exists) {
           // 404 missing files
           res.writeHead(404, {'Content-Type': 'text/plain' });
           res.end('404 Not Found');
           return;
        }
        // set the content type
        var ext = path.extname(action);
        var contentType = 'text/plain';
        if (ext === '.gif') {
           contentType = 'image/gif'
        }
        res.writeHead(200, {'Content-Type': contentType });
        // stream the file
        fs.createReadStream(filePath, 'utf-8').pipe(res);
      });
    }).listen(8080, '127.0.0.1');
    

提交回复
热议问题