Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
Nodejs public folder always fails silently

I'm trying to include an icon as part of my website, currently my code looks like the following:

app.js

const http = require('http');
const fs = require('fs');
const express = require('express')
const path = require('path')

const hostname = '127.0.0.1';
const port = 3000;
const html_file = "./index.html";

var app = express()
app.use(express.static(path.join(__dirname, 'public')));
//app.use(express.static('public'));
console.log(path.join(__dirname, 'public'));

fs.readFile(html_file, function (err, html)  {
    if (err) {
        throw err;
    }
    const server = http.createServer((req, res) => {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/html');
      res.write(html);
      res.end();
    }).listen(port);
console.log(`Listening on http://${hostname}:${port}`)
});

While my html file looks like this:

<!DOCTYPE html>
<html>
<head>
    <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <body>
<p>test text</p>
    </body>
</html> 

However, the icon is never loaded properly. I can see that the request returns in the network inspection tab, and there are no errors from nodejs in the console, but no matter what it fails.

I've tried switching between adding and not including the /public/ in the link line too, as well as moving the HTML file to the public folder itself.

Any ideas?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You're starting a vanilla HTTP server that only serves your index.html file and nothing else.

I'd suggest moving index.html into the public folder and using app.listen() to start your Express app instead.

const express = require("express");
const path = require("path");

const app = express();
const port = 3000;

app.use(express.static(path.join(__dirname, "public")));

app.listen(port, () => {
  console.log(`Listening on port ${port}`);
});

I highly recommend working through the Express Getting Started guide.


You should also use an absolute path to your icon in the HTML

<link rel="icon" type="image/x-icon" href="/favicon.ico">
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!