Cannot find module 'hbs', express-handlebars - node.js

I am trying to use express-handlebars view engine for express and I keep getting the following error:
Error: Cannot find module 'hbs'
at Function.Module._resolveFilename (module.js:538:15)
at Function.Module._load (module.js:468:25)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at new View (C:\Users\WilPrim\Desktop\node-app\node_modules\express\lib\view.js:81:14)
at Function.render (C:\Users\WilPrim\Desktop\node-app\node_modules\express\lib\application.js:570:12)
at ServerResponse.render (C:\Users\WilPrim\Desktop\node-app\node_modules\express\lib\response.js:1008:7)
at C:\Users\WilPrim\Desktop\node-app\routes\routes.js:5:6
at Layer.handle [as handle_request] (C:\Users\WilPrim\Desktop\node-app\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\WilPrim\Desktop\node-app\node_modules\express\lib\router\route.js:137:13)
Here is my Code:
const express = require("express");
const bodyParser = require("body-parser");
const hbs = require("express-handlebars");
const router = require("./routes/routes");
//set up express app
var app = express();
app.use(bodyParser.json());
app.set('view engine', 'hbs');
app.set('views', './views');
app.set('view options', {layout: './layouts/layout'});
app.use(router);

According to the express-handlebars documentation, you have to setup and register the view engine manually:
var express = require('express');
var exphbs = require('express-handlebars');
var app = express();
var hbs = exphbs.create({ /* config */ });
// Register `hbs.engine` with the Express app.
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
// ...still have a reference to `hbs`, on which methods like `loadPartials()`
// can be called.
Looking a little bit further down in the documentation, looks like you can still use the .hbs extension with a bit of configuration:
var express = require('express');
var exphbs = require('express-handlebars');
var app = express();
app.engine('.hbs', exphbs({extname: '.hbs'}));
app.set('view engine', '.hbs');

use command -- sudo npm link hbs

you might have named the main folder as "express"
just change the name of folder,delete "package.json" and try
"npm install" again and then
"npm install express"
"npm install hbs"

/* been using this format for some time now, never had problems */
// import system modules
const hbs = require('express-handlebars');
const express = require('express');
const app = express();
// configuring express-handlebars as hbs
app.engine('hbs', hbs.create({
extname: 'hbs',
defaultLayout: 'main'
}).engine)
// system(app) routes
app.get('/', (req, res, next)=>{
res.render('home', {title: 'HBS TITLE'});
});
// system listening port
app.listen(8080);

install this module on terminal --> npm i hbs

try npm install and npm audit fix multiple times then rum the server after ex

Related

Why is handlebars not working in Node.js?

I have written the line:
app.engine('hbs',hbs({extanme:'hbs',defaultLayout:'layout',layoutsDir:__dirname+'/views/layout/',partialsDir:__dirname+'/views/partials/'}));
And I have assigned:
var hbs= require('handlebars');
The error I get is:
hbs is not a function
Try something like this
npm i hbs // install hbs package
//app.js
const express = require('express')
const path = require('path')
const hbs = require('hbs')
const app = express()
// View Engine Setup
app.set('views', path.join(__dirname))
app.set('view engine', 'hbs')
app.get('/', function(req, res){
res.render('Home', {
array: ['One', 'Two', 'Three', 'Four'],
message: 'Greetings from geekforgeeks'
})
})
app.listen(8080, function(error){
if(error) throw error
console.log("Server created Successfully")
})
For your app.engine after referencing the NPM express-handlebar docs here: https://www.npmjs.com/package/express-handlebars. You need to add a .engine to your hbs constant.
try this!
var hbs= require('handlebars');
app.engine('hbs', hbs.engine('your config stuff here'));
If your still running into issues. Try using express-handlebars (npm install express express-handlebars) with express, then require them like you do. Then it should work
Try This!!
Add hbs.engine
app.engine('hbs',hbs.engine({extname:'hbs',defaultLayout:'layout',layoutsDir:__dirname+'/views/layout/',partialsDir:__dirname+'/views/partials/'}));
And assign:
var hbs= require('express-handlebars');

Why is Express isn't able to find ejs in netlify lambda serverless

I am trying to deploy a project with using serverless http with netlify. So far I have gotten the deployment to be successful, but the page says "Internal server error" and when I check the console, it says "Cannot find module ejs". I have tried to reinstall ejs and express even globally and have moved the "node_modules" folder a level above, but still no luck.
Here is my code:
require('dotenv').config()
const express = require('express')
const app = express()
const port = 3000;
const bodyParser = require('body-parser')
const router = require('./routes')
const path = require('path')
const ejs = require('ejs');
const serverless = require('serverless-http');
app.use(express.static(path.join(__dirname, "/public")))
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use('/.netlify/functions/index', router)
app.set('view engine', 'ejs')
module.exports.handler = serverless(app);
So I put app.set('view engine', 'ejs') and it says that it cannot find ejs
However, this does work on normal
node index.js
but I don't know why it isn't working here.
Help would be appreciated, thank You so much!!!
You forget to say where the folder for the views exist
This should fix it
// view engine setup
app.set('views', path.join(__dirname, 'views')); \\ views being the name of the folder in the root dir
app.set('view engine', 'ejs');

Setting up MEAN stack not rendering app-root

I'm trying to setup a basic mean stack by following this guide, but the client doesn't seem to render the app instead the body contains,
<body>
<app-root></app-root>
</body>
The file structure is exactly the same as a blank angular cli project except the addition of two extra files.
PLUS: npm install --save ejs cors express body-parser
routes/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index.html');
});
module.exports = router;
server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cors = require('cors')
var index = require('./routes/index');
// app
var app = express();
// cors
app.use(cors());
// views
app.set('views', path.join(__dirname, 'src'));
// engine
app.set('view enginer', 'ejs');
app.engine('html', require('ejs').renderFile);
// angular dist
app.use(express.static(__dirname + '/dist'));
// body bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
// route
app.use('/', index);
// Initialize the app.
var server = app.listen(process.env.PORT || 3000, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
I run an ng build and node server.js but get a blank white page in the browser.
Perhaps there is a breaking change that I'm not aware of since that guide was using angular2 (I'm using angular 6).
Since your index.html isn't directly inside the dist folder (rather, it is inside a sub-folder for some reason), try changing app.use(express.static(__dirname + '/dist')); to app.use(express.static(__dirname + '/dist/<your project name here>'));

express post method not working with Content-Type:multipart/form-data

After search all i got tired
can anyone tell me why post method not working when i add Content-Type:multipart/form-data in postman.Note without adding this suck everything works fine. here is my app.js
var app = express();
var apiRoutes = require('./routes/apiRoutes');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded([{extended: false}, {limit: '50mb'}]));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'uploads')));
app.use(multipart());;
app.use(apiRoutes)
here is my apiRoutes.js
var express = require('express');
var router = express.Router();
var fn = require('../webservices');
var multipart = require('connect-multiparty')();
router.post('/api/login', fn.test);
module.exports = router;
and here is my webservices.js
function test(req,res){
console.log("hello there");
}
module.exports = {
test
}
and this show error
TypeError: this[("visit" + node.type)] is not a function
Please report this entire error and stack trace to https://github.com/jadejs/jade/issues
at Object.visitNode (/home/ais/Acruss-NodeJs/node_modules/jade/lib/compiler.js:225:37)
at Object.visit (/home/ais/Acruss-NodeJs/node_modules/jade/lib/compiler.js:212:10)
at Object.visitBlock (/home/ais/Acruss-NodeJs/node_modules/jade/lib/compiler.js:295:12)
at Object.visitNode (/home/ais/Acruss-NodeJs/node_modules/jade/lib/compiler.js:225:37)
at Object.visit (/home/ais/Acruss-NodeJs/node_modules/jade/lib/compiler.js:212:10)
at Object.compile (/home/ais/Acruss-NodeJs/node_modules/jade/lib/compiler.js:66:10)
at parse (/home/ais/Acruss-NodeJs/node_modules/jade/lib/index.js:114:19)
at Object.exports.compile (/home/ais/Acruss-NodeJs/node_modules/jade/lib/index.js:205:16)
at handleTemplateCache (/home/ais/Acruss-NodeJs/node_modules/jade/lib/index.js:174:25)
at Object.exports.renderFile (/home/ais/Acruss-NodeJs/node_modules/jade/lib/index.js:380:10)
so everything you need for using ftp is
here
i recommend you to read this

Using stylus middleware with express 4, SyntaxError

Im trying to use nodejs express v4 with stylus, but its throwing SyntaxError. Please help, also you can find my server.js below;;
Please note: Im first time creating MEANstack project, and dont be harsh on me :)
Your environment has been set up for using Node.js 0.10.26 (x64) and npm.
Error: Most middleware (like logger) is no longer bundled with Express and must
be installed separately. Please see https://github.com/senchalabs/connect#middle
ware.
at Function.Object.defineProperty.get (C:\Sites\meanProject\node_modules\exp
ress\lib\express.js:89:13)
at Object.<anonymous> (C:\Sites\meanProject\server.js:10:17)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
server.js:
var express = require('express');
var stylus = require('stylus');
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
//set view engine
app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
//style middlware
app.use(stylus.middleware({
src: __dirname + '/public',
dest: __dirname + '/public/css',
compile: function compile(str, path){
return stylus(str).set('filename', path).set('compress', true);
}
}));
app.use(express.static(path.join(__dirname + '/public')));//all public req will be responded by public dir now.
//load route
app.get('*', function(req, res){
res.render('index');
});
//start listening on server
var port = 3000;
app.listen(port);
console.log('Server running at localhost:' + port);
#thyforhtian yes, you were right my code was outdated.
I fixed it.
Im not using nodejs to compile my stylus file anymore, instead im using gulp.
Posting my file here, with steps, it might be helpful for someone-else.
Compile stylus files with gulp watch. And code for express server js file
Started with installing node modules
npm init
npm install -save express jade
// Step 1: Install gulp globally
npm install -g gulp
// Step 2: Install gulp in your project
npm install --save-dev gulp gulp-stylus gulp-plumber
npm install morgan body-parser --save
server.js
var express = require('express');
var stylus = require('stylus');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
//set view engine
app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.urlencoded());
app.use(cookieParser());
//all public req will be responded by public dir now.
app.use(express.static(__dirname + '/public'));
//load route
app.get('*', function(req, res){
res.render('index');
});
//start listening on server
var port = 3000;
app.listen(port);
console.log('Server running at localhost:' + port);
gulpfile.js
var gulp = require('gulp');
var stylus = require('gulp-stylus');
var plumber = require('gulp-plumber');
gulp.task('stylus', function() {
gulp.src('public/stylesheets/style.styl')
.pipe(plumber())
.pipe(stylus())
.pipe(gulp.dest('public/stylesheets'));
});
gulp.task('watch', function() {
gulp.watch('public/stylesheets/*.styl', ['stylus']);
});
gulp.task('default', ['stylus', 'watch']);
run gulp to execute
There seem to be a comma missing after src: __dirname + '/public'.
UPDATE
You should require and use it like this (first add it to package.json and npm install):
var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
app.use(logger('dev'));
app.use(bodyParser());

Resources