Setting up the file extension name with Express Handlebars

My handlebars setup seems to be encountering an issue

const path = require('path')
const exphbs = require('express-handlebars')

const morgan = require('morgan');
const multer = require('multer');
const express = require('express');
const erroHandler = require('errorhandler')
const routes = require('../routes/index');

module.exports = app => {

    app.set('port', process.env.PORT || 80) 
    app.set('views', path.join(__dirname, '../views'));
    app.engine('.hbs', exphbs({
        defaultLayout: 'main',
        partialsDir: path.join(app.get('views'), 'partials' ),
        layoutDir: path.join(app.get('views'), 'layouts'),
        helpers: require('../helpers')
    }))
    app.set('view engine', '.hbs');


    // middlewares
    app.use(morgan('dev'));
    app.use(multer({dest: path.join(__dirname, '../public/upload/temp')}).single('image'))
    app.use(express.urlencoded({extended: false}));
    app.use(express.json());

    //routes
    routes(app)

    // static files
    app.use('/public', express.static(path.join(__dirname, '../public')));


    // errorhandlers
    if ('development' === app.get('env')) {
        app.use(erroHandler)
    }

    return app;
}

Despite following the correct directory structure, the error message I receive is:

Error: ENOENT: no such file or directory, open 'C:\Users\Diesan Romero\Desktop\redsocial\views\layouts\main.handlebars'

I've checked my directories multiple times, but can't seem to figure out what's causing this issue. https://i.sstatic.net/ApTyk.png

Answer №1

To ensure that your handlebars files with the extension .hbs work correctly, it's important to specify the extName parameter when setting up handlebars:

exphbs.create({
    extname: '.hbs',
    // include other options as needed
})

You can also adjust your code as follows:

app.engine('.hbs', exphbs({
    extName: '.hbs',
    defaultLayout: 'main',
    partialsDir: path.join(app.get('views'), 'partials' ),
    layoutDir: path.join(app.get('views'), 'layouts'),
    helpers: require('../helpers')
}))

Alternatively, consider renaming your handlebars files to use the extension filename.handlebars.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Elevate your website's design with Vue and create eye-catching CSS

I've been working on a Vue hamburger menu component, but I'm facing an issue with the animations. The animation process seems to reach the desired end result, yet there is no actual animation displayed. The animation triggering is done through a ...

Grant the "User" the ability to modify both images and prices

I'm currently working on an art website for a relative and I am looking to provide them with the ability to log in and easily update the images of their paintings as well as adjust the pricing. Is it possible to enable this functionality? My assumptio ...

What is the best way to obtain the clicked ID when a user clicks on an element within

As a budding web developer, I've been working on a code snippet to dynamically load data into an iframe: $(document).ready(function () { function loadMaterials(type, query) { $.ajax({ type: 'GET', url: &ap ...

Using the DRY principle in JavaScript to handle dynamic fields

Recently delving into Javascript, I encountered a dynamic field script that allows for adding and subtracting fields with the click of a button. The functionality is effective and serves its purpose well. $(document).ready(function() { var max_fields ...

Utilize dynamic Google Maps markers in Angular by incorporating HTTP requests

Struggling to find a solution for this issue, but it seems like it should be simple enough. Initially, I fetch my JSON data using the code snippet below: testApp.controller("cat0Controller", function($scope, $http){ var url = "../../../Data/JSONs/randomd ...

Using ng-class in Angular.js with a boolean retrieved from a service: A step-by-step guide

I need to dynamically set a class based on a boolean value that is determined in a service. This example is simplified for readability, but in reality, the boolean would be set by multiple functions within the service. Here is how it would look in HTML: ...

Error message: Next.js - Unable to access properties of an undefined object (user)

I am currently utilizing Next.js and Next-auth in my current project. Within this project, I am working on creating a Sidebar component that will display a list of items specific to each user. To achieve this, I am using the useSession hook to retrieve t ...

I received a "quota exceeded" message from Mongolab, even though I had only used up half of my allotted storage space

I have set up a Sandbox database for an amateur project that I am working on for a competition. This is my first time doing something like this, and unfortunately, I made the mistake of waiting until the very end to upload all the records I need for analys ...

What steps do I need to take to develop a syntax similar to Vue.js using only plain JavaScript?

<div id=""> <span>{{msg}}</span> </div> Assume that {{msg}} is a variable in JavaScript. Now, I aim to locate the parent tag of {{msg}} and replace its content with a new value using innerHTML, where {{msg}} serves as an identi ...

Ensuring seamless user recognition when redirecting them to a new HTML page

In our web application, new users are assigned a standard password upon registration. Upon logging in with the standard password, they are automatically redirected to a 'change Password' page where they can update their password. However, we hav ...

What is the best way to make a drop down menu list appear when I click on the parent li, and then show the sub li using JavaScript?

I have a code that includes an image, HTML, and CSS code. Can anyone please tell me how I can set up a drop-down menu list to open the sub <li> elements when I click on a parent <li> using JavaScript? You can see the appearance of the code in t ...

js issue with passing form data to use with PHP mail function

As a novice, I am diving into the world of HTML webpage creation. Utilizing a free online template, my current project involves developing a Contact Page that triggers a php script to send an email with the captured fields. While I've successfully man ...

Enabling Cross-Origin Resource Sharing in Node.js 14

I'm diving into the world of JavaScript and Node.js as I work on creating a new REST-based API using NodeJS. However, I've hit a roadblock when trying to fetch data from the API due to a CORS issue. Browser console error message: Access to fetch ...

Recording videos using the Safari Browser

Within my ReactJs application, I have integrated react-multimedia-capture, a package that utilizes navigator.mediaDevices.getUserMedia and the MediaRecorder API to facilitate video recording. While I am successfully able to record videos on Chrome, Safari ...

Utilizing Facebook's UI share URL parameters within the Facebook app on mobile devices

Encountering an issue with the Fb ui share functionality on certain smartphones Here is the function: function shareFB(data){ FB.ui({ method: 'share', href: data, }, function(response){}); } Implemented as follows: $urlcod ...

In Javascript, when trying to call Firebase database child(), it may sometimes result in the return value being "

Here is the current setup: Firebase Database: setores: { -KkBgUmX6BEeVyrudlfK: { id: '-KkBgUmX6BEeVyrudlfK', nome: 'test' } -KkDYxfwka8YM6uFOWpH: { id: '-KkDYxfwka8YM6uFOWpH', nome ...

I'm baffled by why I keep receiving the error message "Unknown provider: $routeProvider <- $route <- AppController" in AngularJS, even though I have already

I've exhausted all the solutions I found on stackoverflow without success. Apologies if this is a duplicate question. My goal is to reset the content of my Bootstrap table with a button click using the function $route.reload(). However, when I includ ...

Troubleshooting issue with error handling in graphql mutation hook with react and apollo is not resolving

It seems like I might have overlooked a configuration in my code, but I can't seem to pinpoint where I went wrong. In our application, we have a basic login form. If the correct username and password are entered, everything works smoothly. However, ...

Prevent Duplicate Service Instances in Angular

After doing some thorough research online, I've identified the root of my issue: multiple instances of a particular service are being created. I need assistance in pinpointing and rectifying this problem within my code. The secondary service is depen ...

Steps to eliminate the x icon from the text box that appears automatically in Internet Explorer

I'm currently working with a UI5 text box that includes a built-in option for clearing the text using a 'X' button. However, I've noticed that in Internet Explorer, an additional default cross mark is being added alongside the UI5 cros ...