Run ejs-lint automatically on error in express - node.js

I am using ejs with express, and there is an error in my ejs code
SyntaxError: Unexpected token '.' in
.../views/pages/index.ejs while compiling ejs
If the above error is not helpful, you may want to try EJS-Lint:
https://github.com/RyanZim/EJS-Lint
And yep, that was a pretty unhelpful error, so I added ejs-lint to my server.js file:
const express = require('express');
const app = express();
const dotenv = require('dotenv');
const ejs = require('ejs');
const ejsLint = require('ejs-lint');
// setup configs
dotenv.config();
const config = process.env;
app.set('view engine', 'ejs');
// routes
app.get('/', function (req, res) {
try {
console.log('attempting to render');
res.render('pages/index');
} catch (e) {
console.log('Should get here'); // this line is never hit
}
});
// gotta get yourself connected
app.listen(config.port, () =>
console.log(`Example app listening at http://localhost:${config.port}`)
);
But the try/catch isn't working and it would be great if this was somehow integrated with express render.

Related

localhost:5000 server is just keep loading and not showing ejs template

I am still learning Node.js. I created a server using express documentation and it worked before.
But now for a project I have imported some npm packages. like dotenv, http-errors, ejs and others. I created (.env) file and there decleared PORT=5000, import it in my (main.js) file and called app.listen function. So that, it can show my ejs template in the browser but when i hit http://localhost:5000 it just keeps loading but nothing appears. it's not giving any errors in the terminal either, it just keeps loading unless i press ctrl+c in my terminal.
main.js
const express = require("express");
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const path = require("path");
const cookieParser = require("cookie-parser");
const { notFoundHandler, errorHandler } = require("./middlewares/common/errorHandler");
const app = express();
dotenv.config();
//database connection
mongoose.set("strictQuery", true);
mongoose.connect(process.env.MONGO_CONNECTION_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("Database Conntcted!"))
.catch(err => console.log(err));
app.use(express.json);
app.use(express.urlencoded({ extended: true }));
app.set("view engine", "ejs");
app.set('views', 'views');
app.use(express.static(path.join(__dirname, "public")));
app.use(cookieParser(process.env.COOKIE_SECRET));
app.use(notFoundHandler);
//common error handler
app.use(errorHandler);
app.listen(process.env.PORT, () => {
console.log(`app is listing at port ${process.env.PORT}`);
});
my errorhandler.js
const createError = require("http-errors");
function notFoundHandler(req, res, next) {
next(createError(404, "CONTENT WAS NOT FOUND!"));
}
function errorHandler(err, req, res, next) {
res.render("error", {
title: "Error Page",
});
}
module.exports = {
notFoundHandler: notFoundHandler,
errorHandler,
};
error.ejs
my ejs file route ("./views/error.ejs")
<title><%= title %></title>
<body>
Alart!
</body>
.env file
PORT=5000
problem fixed! The problem was in my main file. There was a parentheses() missing.
it would be app.use(express.json());

TypeError: handlebars is not a function error

I am a newbie of node.js, i use template engine express-handlebar but i get problem is: **TypeError: handlebars is not a function at Object. ** . I have search lot but not any answer to fix. my code is below:
const morgan = require('morgan');
const handlebars = require('express-handlebars');
const app=express();
const port =3000;
// hTTP logger
app.use(morgan('combined'));
//templace engie
app.engine('handlebars',handlebars());
app.set('view engine','handlebars');
app.get('/',(req,res)=> {
return res.send('hello world');
});
app.listen(port,()=>console.log(`Example app listening at http://localhost:${port}`));````
For version 6.0.2, the express-handlebars package exports create, engine function. See source code The basic usage should be:
const { engine } = require("express-handlebars");
const express = require("express");
const app = express();
const port = 3000;
//templace engie
app.engine("handlebars", engine());
app.set("view engine", "handlebars");
app.get("/", (req, res) => {
return res.send("hello world");
});
app.listen(port, () =>
console.log(`Example app listening at http://localhost:${port}`)
);

problem at rendering views using express.js

Though my rendering path is correct when I hit http://localhost:4444/admin/posts/create it shows some error like
Error: Failed to lookup view "/admin/posts/create" in views directory "D:\node practise\CMS\views"
app.js file is like
const express = require('express');
const app = express();
const path = require('path');
const exphbs = require('express-handlebars');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/cms', { useNewUrlParser: true })
.then(db => {
console.log('MONGO CONNECTED!');
})
.catch(error => {
console.log('MONGO NOT CONNECTED!');
})
//making app to use static file
app.use(express.static(path.join(__dirname, 'public')));
//define template engine
app.set('view engine', 'handlebars');
//set default engine
app.engine('handlebars', exphbs({defaultLayout: 'home'}));
//load routes
const home = require("./routes/home/index");
const admin = require("./routes/admin/index");
const posts = require("./routes/admin/posts");
//use routes
app.use(home);
app.use("/admin", admin);
app.use("/admin/posts", posts);
//setting up server
app.listen(4444, () => {
console.log('Listening....');
});
I have posts.js that handles this route like
const express = require("express");
const router = express.Router();
router.all('/*', (req, res, next) => {
req.app.locals.layout = 'admin';
next();
})
router.get('/', (req, res) => {
res.send('It works!');
})
router.get('/create', (req, res) => {
res.render('/admin/posts/create');
})
module.exports = router;
And I have my views folder structure as
What may be the cause of error? When I try to send response it works but when I try to render the view it shows error.
Can you try res.render('admin/posts/create');?
If the view folders is set properly like this: app.set('views', './views'), you should be able to resolve simple view name like res.render('myview') under ./views folder

app.get is not a function in express.js

I am actually not able to figure it out that why in index.js file in below code snippet is throwing me an error : app.get is not a function.
Please help me out..
//here is my app.js file
const express = require('express');
const app = express();
const helpers = require('./helpers');
const routes = require('./index')
app.use((req, res, next) => {
app.locals.h = helpers;
next();
});
app.use('/', routes);
app.set('views',(__dirname));
app.set('view engine', 'pug');
app.listen(3000,()=>console.log('port 3000'));
module.exports = app;
//here is my index.js file
const app = require('./app')
app.get('/',(req,res) => {
res.render('template');
})
module.exports = router;
//helpers.js
exports.title = "NODEjs";
//template.pug
doctype html
html
head
title=`${h.title}`
body
h1 myHeading #{h.title}
You have a circular dependency loop and rather than create an infinite loop, the require() subsystem detects that and fails to load your module.
In app.js, you load index.js. In index.js, you load app.js. Circular dependency loop.
There are two separate techniques that can be used to solve your particular problem. You appear to be using about some of one technique and some of another and that creates your problem.
A classic way to define new routes in a separate file is to just have that file create and export its own router. It then assigns the routes to the router (not to app) and thus that other file never needs the app object at all. Because you show module.exports = router, it appears you have part of that technique, but only part of it.
Here's how the code would work to do it that way:
// app.js
const express = require('express');
const app = express();
const helpers = require('./helpers');
app.use((req, res, next) => {
app.locals.h = helpers;
next();
});
// hook in routes from the index.js router
app.use('/', require('./index'));
app.set('views',(__dirname));
app.set('view engine', 'pug');
app.listen(3000,()=>console.log('port 3000'));
// index.js
const router = require('express').Router();
router.get('/',(req,res) => {
res.render('template');
});
module.exports = router;
You could also pass app to index.js when you load it rather than having it try to import app. This also solves the circular dependency issue.
const express = require('express');
const app = express();
const helpers = require('./helpers');
// pass app here so it can register routes
require('./index')(app);
app.use((req, res, next) => {
app.locals.h = helpers;
next();
});
app.use('/', routes);
app.set('views',(__dirname));
app.set('view engine', 'pug');
app.listen(3000,()=>console.log('port 3000'));
Change index.js to export a module constructor which you call and pass app to:
module.exports = function(app) {
app.get('/',(req,res) => {
res.render('template');
})
}
Add parenthesis on the first line :
const express = require('express')();
The first answer should be accepted.
This is happening only due to the circular dependencies in this case.

call require not possible in other file .js for nodeJs and express project

In project nodeJS - express, after install module by npm, when require "create-file" module in app.js const cf = require('create-file') , i can't use it in main.js, in console i have this return cf is not defined when i run node.
app.js
` const express = require('express');
const ejs = require('ejs');
const bodyParser = require('body-parser');
const cf = require('create-file');
// init app
const app = express();
//Template engine setup
app.set('view engine','html');
app.engine('html',ejs.renderFile);
// Index route
app.get('/',(req, res) => {
res.render('index.html');
})
// Public folder setup
app.use(express.static(__dirname + '/public'));
// Body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// Catch from submit
app.post('/', (req, res) => {
res.send(req.body);
})
// Define port
const port = 3030;
// Start server
const server = app.listen(port, () => console.log( 'Server start on port
3030 '));`
main.js
`const button12 = document.getElementById('button');
button12.onclick = function () {
cf('C:\Users\tmeda\Bureau\fileTest.txt', 'my content\n', function (err) {
// file either already exists or is now created (including non existing
directories)
});
}`
Define Your Variable as global in in your app.js file
like global.cf = require('create-file');
So this way you can access cf variable in any files , no need to require it again in different file .

Resources