Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set favicon in HTTP server?

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)

like image 568
baranskistad Avatar asked Sep 17 '16 23:09

baranskistad


People also ask

How do I add a favicon to my server?

To add a favicon to your website, either save your favicon image to the root directory of your webserver, or create a folder in the root directory called images, and save your favicon image in this folder. A common name for a favicon image is "favicon.ico".

Which HTML tag is used to set the favicon?

A favicon is added in the <head> tag of a web page. The <head> tag is where all the so-called “meta” information goes. Meta information is details about the web page itself, such as the title of the page.


1 Answers

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);
like image 71
noisypixy Avatar answered Oct 21 '22 08:10

noisypixy