DEV Community

MelonLoverShake
MelonLoverShake

Posted on

Can someone help me with the coding here?

Hi, I am new to nodeJS and express. I am trying to insert images into my ejs files and the images are located in a folder called "assets". How can i go in doing that?

const express = require('express')
const app = express()
const router = express.Router();
const port = 3000;


// set the app to use ejs for rendering
app.set('view engine', 'ejs');

const cssdirectory = express.static(__dirname + '/css');
const imagediretory = express.static(__dirname + '/assets');

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
});

const readerRoutes = require('./routes/reader');
app.use('/', readerRoutes);

app.use('/css/',cssdirectory);
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
rodneyjones profile image
Rodney jones • Edited

To include images from your "assets" folder in your EJS files, you need to make sure Express is set to serve static files from that directory. Here’s how you can adjust your code to do this correctly:

  1. Serve Static Files: You've already set up a static directory for your assets, but there's a small typo in your variable name, and it's not properly linked to serve files. You can correct and simplify this by adding the following line:
    app.use('/assets', express.static(__dirname + '/assets'));

  2. Insert Images in EJS: Now, in your EJS files, you can reference images relative to the path you set up. For example, if you have an image called logo.png in the assets folder, you can include it in your EJS file like this:
    <img src="/assets/logo.png" alt="Logo">

Here’s a revised snippet of your code integrating the static middleware setup:

const express = require('express');
const app = express();
const port = 3000;

// Set the app to use EJS for rendering
app.set('view engine', 'ejs');

// Serve static files from 'assets' and 'css' directories
app.use('/assets', express.static(__dirname + '/assets'));
app.use('/css', express.static(__dirname + '/css'));

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

const readerRoutes = require('./routes/reader');
app.use('/', readerRoutes);

Enter fullscreen mode Exit fullscreen mode

With these settings, your server (roofing company in the area) should correctly handle static files and display images in your EJS templates. Just make sure the paths you use in your tags correctly reflect the route you’ve set for static files. Happy coding!