RubeOnRails
RubeOnRails

Reputation: 1163

How to render html and javascript from express?

I have a very simple express app that has two routes, one that should render html, and one that should render a javascript file. Ideally, I'd like to have each in different folders, a ./views folder for html and an ./assets/javascripts folder for js. I'm wondering the best way to do this? Here is what I have so far:

var express = require('express')
  , app     = express()
  , fs      = require('fs')

['html', 'js'].forEach(function(extension) {
  app.engine(extension, function(filePath, options, callback) {
    fs.readFile(filePath, function(err, content) {
      if (err) throw new Error(err)
      return callback(null, content.toString())
    })
  })
})

app.set('views', './views')
app.set('view engine', 'html')

app.get('/', function(req, res) {
  res.render('index')
})

app.listen(3000)

Do I need to be doing this? Where can I find more information?

Upvotes: 0

Views: 481

Answers (2)

graemeboy
graemeboy

Reputation: 610

For static JavaScript files, you just need to set your public assets folder, as such:

app.use(express.static(__dirname + '/public'));

I suggest you read the API documentation further: http://expressjs.com/api.html

Upvotes: 1

Faiz Ahmed
Faiz Ahmed

Reputation: 1103

If you are just trying to make routes that respond to a static file. Use:

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/path-to/your/static-file');
});

If you just want to set assets for your project. You should do:

app.use(express.static(__dirname + '/public'));

And then use a dedicated public directory for your assets.

(If this wasn't the answer you were looking for ask me in comments what you want!)

Upvotes: 1

Related Questions