Images not showing up with nodejs express on ubuntu server

August 24, 2018 2.1k views
Programming Project JavaScript Node.js Development Ubuntu 16.04 DigitalOcean

Problem:
Images show up as broken icons. The images work perfectly fine when run locally on my own (windows 10) desktop, but on the ubuntu server it doe snot seem to work right.

Things to Note:

  • File path is correct (not getting a 404 not found error when checking the status codes on the images)
  • It works fine for ’.ico’ files that are in the same directory as the other images

Example Code With Same Problem:
I recreated a simplified version of code that has the same issue as my bigger project.
The folder structure for this test was as follows:

testServer
└> node_modules
└> favicon.ico
└> pattern.png
└> index.js

This code below works and you see a page with the ‘favicon.ico’ image on it:

const express = require('express');
const app = express();

app.get('/', (req, res) => res.sendFile(__dirname + '/favicon.ico'));

app.listen(3000, () => console.log('Example app listening on port 3000!'));

However, changing the 'favicon.ico’ image to the 'pattern.png’ image from the same directory causes an issue. There is no 'ERROR: no such file or directory’ message that shows up, it just goes to a similar page that you get from the code above. However, in place of where the 'pattern.png’ should be, there is nothing but an empty space with a white box outline around it. So it knows that the file with that path exists, but it does not show it properly

This is the code that does not work correctly:

const express = require('express');
const app = express();

app.get('/', (req, res) => res.sendFile(__dirname + '/pattern.png'));

app.listen(3000, () => console.log('Example app listening on port 3000!'));

Am I missing something obvious? I assume that the JavaScript code is not an issue, but more likely its a Windows vs Linux environment difference. If anyone has any thoughts on what might be the issue I would appreciate the help!

1 Answer

Well now I feel silly. After hours of trying to narrow down the problem I finally found it! In case anyone else has a similar issue to me, this was how I fixed it. The whole problem was with the way I was with my FTP. I use WinSCP to upload files and it was defaulting to a ‘Text’ transfer mode instead of binary. So I had to re-upload my images with the correct transfer mode (binary, instead of text) and now they finally show up.

Have another answer? Share your knowledge.