Set favicon in HTTP server?

2019-03-31 07:10发布

问题:

I'm using Node.js HTTP module to create a server, and I'm wondering, how do I set the favicon (shortcut icon) in a HTTP server? I searched this up, and I saw that Express can set the favicon, but I didn't find any HTTP solution.

How do I accomplish this? (Without migrating to Express)

回答1:

It boils down to this:

  • If the requested path is that of your favicon, serve it.
  • Otherwise, do whatever you're doing with the requests.

Unless you change the path to your favicon in an HTML document, browsers will (usually) make a request to the /favicon.ico path in order to get the favicon of your server.

That means, serving your favicon at /favicon.ico is often enough.

Assuming your favicon is located at ./public/favicon.ico, and will be served at the /favicon.ico path in your server, you can do something like this:

var http = require('http');
var path = require('path');
var fs = require('fs');
var url = require('url');

var server = http.createServer();

// Location of your favicon in the filesystem.
var FAVICON = path.join(__dirname, 'public', 'favicon.ico');

var server = http.createServer(function(req, res) {
  var pathname = url.parse(req.url).pathname;

  // If this request is asking for our favicon, respond with it.
  if (req.method === 'GET' && pathname === '/favicon.ico') {
    // MIME type of your favicon.
    //
    // .ico = 'image/x-icon' or 'image/vnd.microsoft.icon'
    // .png = 'image/png'
    // .jpg = 'image/jpeg'
    // .jpeg = 'image/jpeg'
    res.setHeader('Content-Type', 'image/x-icon');

    // Serve your favicon and finish response.
    //
    // You don't need to call `.end()` yourself because
    // `pipe` will do it automatically.
    fs.createReadStream(FAVICON).pipe(res);

    return;
  }

  // This request was not asking for our favicon,
  // so you can handle it like any other request.

  res.end();
});

// Listen on port 3000.
//
// This line is not relevant to this answer, but
// it would feel incomplete otherwise.
server.listen(3000);