简体   繁体   中英

node.js ejs - Don't render file if it does not exist

I have a views folder structure and a ejs file profile_60113.ejs like this

views
    docs
        profile_60113.ejs

I can dynamically render the file like this (where data.groupID == 60113):

<%- include("docs/profile_" + data.groupID); %>

But how can I first check if the file exists? I tried this:

<% if (fs.existsSync("views/docs/profile_" + data.groupID)) { %>
    <%- include("docs/profile_" + data.groupID); %>
<% } %>

Or ...

<% if (fs.existsSync("docs/profile_" + data.groupID)) { %>
    <%- include("docs/profile_" + data.groupID); %>
<% } %>

But didn't work ... const fs = require('fs') is included in the controller and fs:fs is rendered

What works is eg:

Option 1 (Synchronously): Template

Serverside:

const fs = require('fs');

var getGroupID = 60113;

res.render('docs', {
   page: setPage,
   data: {groupID: getGroupID},
   fs: fs   
});  

Template:

<% if (fs.existsSync("views/docs/profile_" + data.groupID + ".ejs")) { %>
    <%- include("docs/profile_" + data.groupID); %>
<% } %>

Option 2 (Synchronously): Serverside & Template

Serverside:

const fs = require('fs');

var getGroupID = 60113;

var getProfile;
if (fs.existsSync("views/docs/profile_" + getGroupID + ".ejs")) {
  getProfile = true;
} else {
  getProfile = false;
}

res.render('docs', {
   page: setPage,
   data: {groupID: getGroupID},
   profile: getProfile   
});       

Template:

<% if (profile) { %>
    <%- include("docs/profile_" + data.groupID); %>
<% } %> 

Option 3 (Asynchronous I/O): Serverside & Template

Serverside:

...

var getProfile;
try {
  await fs.promises.access("views/docs/profile_" + getGroupID + ".ejs");
  getProfile = true;
} catch (error) {
  console.log(error);
}   

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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