Hick
Hick

Reputation: 36414

Error when rendering HTML in express

I'm trying out a simple one page render and I'm obviously doing it wrong:

var express = require('express');
var app = express();

app.get('/', function(req, res){
   res.render('home.html');
});

app.listen(3000);
console.log('Listening on port 3000');

Error:

Error: Cannot find module 'html'

I want to load a page with CSS/images and wanted to know where to store the CSS/images/scripts/HTML and how to load it. I have yet to find many example express apps.

Upvotes: 2

Views: 1717

Answers (3)

Patrick McGraw
Patrick McGraw

Reputation: 35

You place static HTML files not using any templates in the in the express project public folder and invoke it using:

app.get('/', function(req, res) {
  res.redirect('/home.html');
});

Upvotes: 1

DB Prasad
DB Prasad

Reputation: 795

I want to load a html with css/images and wanted to know what is the layout of where to store the css/img/js and the html and load it? I am yet to find many example express js apps.

Assuming that you have installed express, within your express project you will find public folder. within public folder you will find three folder - images, javascripts, and stylesheets . As the names suggest place your css/img/js in their respective folders.

Upvotes: 1

hexacyanide
hexacyanide

Reputation: 91799

When using res.render, you are rendering a defined view. The documentation state:

Render a view with a callback responding with the rendered string. When an error occurs next(err) is invoked internally.

For specific HTML, you either have to load the file with fs.readFile, or have Express use a rendering engine, such as Jade or EJS. For example, this code sample would apply the EJS render engine to all files with the extension .html.

app.engine('html', require('ejs').renderFile);

Then you can render a file like this. This is an example of passing variables to the HTML file, because that's what embedded JavaScript is used for.

app.get('/', function (req, res) {
  res.render('/file', {
    pass: 'arguments',
    to: 'the file here'
  });
});

That is more convenient than having to read the file on each load like so:

app.get('/', function (req, res) {
  fs.readFile('/index.html', 'utf8', function (err, data) {
    res.send(data);
  });
});

Although this is aside from your question, this is how passing variables to EJS works. It even works with if statements and loops, since it accepts all JavaScript. Putting console.log in the file would log each time the file was rendered.

<span><%= pass %></span>
<!-- after rendering -->
<span>arguments</span>

If you need to serve other resources, such as CSS, JavaScript, or other html files, you could use Express' directory function.

app.use(express.static('/'));

Then you wouldn't need to render your HTML at all. It would be statically served.

Upvotes: 4

Related Questions