I have a Heroku app using Node.js and Express, and I want to determine whether or not a certain file exists. However, it seems like the file is never found. I have the following path:
app.get('/sims/:sim_name', (req, res) => {
var simName = req.params.sim_name; // get the name of the requested sim from the URL
// if it exists, render it
if (fs.existsSync(`pages/sims/${simName}.ejs`))
res.render(`pages/sims/${simName}`);
// otherwise, show an error message
else
res.send("Sorry, the page you requested does not exist.");
});
The directory structure of my project looks like this:
.
├── Procfile
├── README.md
├── app.json
├── index.js
├── node_modules
│ ├── so many node_modues...
├── package-lock.json
├── package.json
├── public
│ ├── images
│ │ └── ...
│ ├── lang-logo.png
│ ├── node.svg
│ ├── scripts
│ │ └── ...
│ ├── stylesheets
│ │ ├── ...
│ └── test.html
├── test.js
└── views
├── pages
│ ├── index.ejs
│ ├── sims
│ │ └── EField.ejs
└── partials
├── header.ejs
└── nav.ejs
I am doing something wrong here? Or is this a Heroku issue?
Advertisement
Answer
Ok, I needed to change pages/sims/${simName}.ejs to views/pages/sims/${simName}.ejs.
I had previously tried /views/pages/sims/${simName}.ejs, which didn’t work because of how the file paths work in Heroku.
I also added braces, as per the suggestion of @UserToday (although this wasn’t necessary).