Is path.join(__dirname, 'views') no longer needed for rendering ejs?

0

Issue

I was doing some testing while following a tutorial, and noticed they did not include:

app.set('views', path.join(__dirname, 'views'));

Is this not needed to render ejs files, or maybe I was using it wrong on my previous project.

The

app.set('view engine', 'ejs');

is there, and it renders the ejs still. I don’t quite understand how this is happening, and couldn’t find anything online either.

Please note, I have a simple Hello World file named index.ejs file in a views folder.
Here is my simple code

const express = require('express');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const flash = require('connect-flash');

const app = express();

const port = process.env.PORT || 4000;

app.use(express.urlencoded({extended: true}));
app.use(express.json());

app.use(cookieParser('SecretStringForCookies'));
app.use(session({
  secret: 'SecretStringForSession',
  cookie: {maxAge: 60000},
  resave: true,
  saveUninitialized: true
}));
app.use(flash());

app.set('view engine', 'ejs');

app.get('/', (req,res) => {
  res.render('index');
});

app.post('/', (req,res) => {
  res.redirect('/');
});

app.listen(port, () => {
  console.log(`App listening on port: ${port}`);
});

Solution

Daniel
If you are using views directory as a root you don’t need to mention in app.js but if you are using partials and other directories at that time you have to mention those directories in app.js with path.

Answered By – Smit Gajera

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More