08 elokuuta, 2020

Serving favicon.ico with node.js easily without express

Sad but true

There are literally hundreds of tips in various places of Internet helping us to get rid of those annoying error messages, where browser is (without success) trying to load favicon.ico -file from node.js-server.  I was looking for some neat code snippet how to do it, but all I found is axamples of how to just block those requests so, that error messages stop, or there was solutions too, but they all were using express, wich imho is way too heavy solution, for minimalist approach. So I continued studying and in one hour I have developed my own solution, which I now proudly present.

Solution

Here is minimal index.js -node server file: 

var http = require("http"),

url = require("url"),

fs = require("fs"),

hostname = "localhost",

port = '8000',

faviconPath = '/img/favicon.ico';


fs.readFile('./index.html', function (err, html) {

    if (err) {

        throw err; 

    }       

    http.createServer(function(request, response) {

     var pathname = url.parse(request.url).pathname;

     if (pathname === '/favicon.ico') {

        var fileStream = fs.createReadStream(__dirname + faviconPath);

        console.log('sending favicon...')

        return fileStream.pipe(response); // send that icon...

     }

        response.writeHeader(200, {"Content-Type": "text/html"});  

        response.write(html);  

        response.end();  

    }).listen(port);

     console.log('Open page in chrome for you... :');

       var childProc = require('child_process');

       childProc.exec('open -a "Google Chrome" http://'+hostname+':'+port+'/');

});


Minimum ready made HTML file 

Make /img -folder inside your project folder and put your favourite favicon.ico -icon in there. Then put this index.html file in same folder with server -file index.js:


<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8">

    <title>Simplest app</title>

    <style>

    body { margin: 0; }

    </style>

</head>

<body>

    <div>

<h1>Welcome</H1>

    See the small favourite icon up there?

</div>

</body>

</html>


Testing

Now you take your terminal app and go to that project folder...


> cd myNodeServerProject


Then you start your server:


> node index


Up and running

Node will start with index.js file and immediately Chrome will fetch your index.html -page from local node-server and if you look at upper area of the page, there is somewhere this very small icon just where it should be. Thou shall never ever see that annoying error message again, AND you have actually learned how to solve the problem, not just put the symptoms under the carpet...


 - You are welcome.