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

Time:10-06

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}`);
});

CodePudding user response:

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.

  • Related