I have a simple web app and when I deploy it freshly or execute it locally it works fine. However, when I kill the pm2 process and start it again with
sudo pm2 start /var/www/thewthr.app/index.js --watch -l /var/log/pm2/thewthr.app.log
it results in:
Error: Failed to lookup view "index" in views directory "public"
at Function.render (/var/www/thewthr.app/node_modules/express/lib/application.js:580:17)
at ServerResponse.render (/var/www/thewthr.app/node_modules/express/lib/response.js:1012:7)
at /var/www/thewthr.app/index.js:35:9
at Layer.handle [as handle_request] (/var/www/thewthr.app/node_modules/express/lib/router/layer.js:95:5)
at next (/var/www/thewthr.app/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/var/www/thewthr.app/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/var/www/thewthr.app/node_modules/express/lib/router/layer.js:95:5)
at /var/www/thewthr.app/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/var/www/thewthr.app/node_modules/express/lib/router/index.js:335:12)
at next (/var/www/thewthr.app/node_modules/express/lib/router/index.js:275:10)
This is my code:
const express = require('express');
const path = require('path');
require('dotenv').config({path: path.join(__dirname, '.env')});
const app = express();
const server = require('http').Server(app);
// start server
server.listen(process.env.PORT, () => console.log(`Express running → PORT ${server.address().port}`));
// start rendering engine
app.set('view engine', 'pug');
app.set('views', 'public');
// define express props
app.use(express.static('public'));
app.use(express.urlencoded({extended: true}));
app.use(express.json());
// render view
app.get('/', (req, res) => {
res.render('index', {
title: `weather ☀`
});
});
Express' views and static files are all relative to the current working directory, which is not the location of the javascript file, but the location from which you ran the file. You can see the cwd with process.cwd()
, and the location of the file with __dirname
, and observe how they are different. There are three possible fixes:
Replace all instances of 'public'
with __dirname + 'public'
or path.join(__dirname, 'public')
. This will use the location of the file as the base directory instead of the cwd and will make it so that your program works regardless of cwd.
Call process.chdir(__dirname)
at the start of your program to change the current working directory to the location of the file, which will also guarantee your program runs correctly regardless of cwd.
Start your program with --cwd /var/www/thewthr.app
in pm2.