1

I have a simple app on Heruku that show an image.

app.js
package.json
package-lock.json
public
   |__ image1.png
   |__ image2.png

Here is the content of app.js

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

app.set('port', (process.env.PORT || 5000));
app.use(express.static('public'));

app.get('/', function(request, response) {
    const today = new Date().getHours();
    const img = today <= 13 ? 'image1.png' : 'image2.png';
    response.sendFile(path.join(__dirname, '../public/' + img));
});

In the Heroku log I get this error: Error: ENOENT: no such file or directory, stat '/public/image1.png'

I have made a lot of tries, following these answers:

None of these do the trick in my case. What could be wrong?

smartmouse
  • 13,912
  • 34
  • 100
  • 166

1 Answers1

1

I think the problem is at this line path.join(__dirname, '../public/' + img)

__dirname return directory location where script is being executed. In your case when you are joining path with '../public' it might be skipping app.js parent dir and selecting app.js parent's parent dir. So use /public instead ../public Try below code

const express = require('express');
const app = express();
const path = require('path');
//app.set('port', (process.env.PORT || 5000));
app.use(express.static('public'));

app.get('/', function(request, response) {
    const today = new Date().getHours();
   const img = today <= 13 ? 'image1.png' : 'image2.png';
   console.log(__dirname);
   console.log(path.join(__dirname, '/public', img))
   response.sendFile(path.join(__dirname, '/public', img));

});
Sandeep Patel
  • 4,815
  • 3
  • 21
  • 37