简体   繁体   English

Node.js:fs.existsSync 在 Heroku 上不起作用

[英]Node.js: fs.existsSync doesn't work on Heroku

I have a Heroku app using Node.js and Express, and I want to determine whether or not a certain file exists.我有一个使用 Node.js 和 Express 的 Heroku 应用程序,我想确定某个文件是否存在。 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?还是这是 Heroku 问题?

The undisciplined way you code is like asking for trouble!乱码的方式就像自找麻烦! Start using curly brackets wherever needed!在需要的地方开始使用大括号!

Here's the corrected script...这是更正后的脚本...

if (fs.existsSync(`pages/sims/${simName}.ejs`)) 

   { res.render(`pages/sims/${simName}`);}

else
   { res.send("Sorry, the page you requested does not exist.");}

Ok, I needed to change pages/sims/${simName}.ejs to views/pages/sims/${simName}.ejs .好的,我需要将pages/sims/${simName}.ejsviews/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.我之前尝试过/views/pages/sims/${simName}.ejs ,但由于文件路径在 Heroku 中的工作方式,它不起作用。

I also added braces, as per the suggestion of @UserToday (although this wasn't necessary).根据@UserToday 的建议,我还添加了大括号(尽管这不是必需的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM