Not able to access static files in express

Issue

I tried to use my fonts folder files inside one of my controller files. fonts folder is inside the public folder. I checked some of the StackOverflow questions and add this code to my app.js file. but somehow it didn’t work for me.

app.use(express.static(__dirname + '/public'));

here is the controller file code in which I try to access these files.

var fonts = {
  Roboto: {
    normal: '/fonts/Roboto-Regular.ttf',
  }
};

var PdfPrinter = require('pdfmake');
var printer = new PdfPrinter(fonts);

This is the error I got when I run the server.

Error: ENOENT: no such file or directory, open '/fonts/Roboto-Regular.ttf'

Solution

A static end point is only going to apply when clients read URLs from the server. It has nothing to do with other server-side JS that reads directly from the filesystem.

You need to use an absolute path (which you could compute relative to the directory the JS file is in with __dirname just like you did when setting up the static end point.

Answered By – Quentin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published