Reading HTML in Node.js

Problem

I'm trying to launch an index.html page with nodejs, but for some reason I keep getting an Application error after I push it to Heroku. Any idea what I have wrong with my code?

 #/!/usr/bin/env node

 var express = require('express');

 var app = express.createServer(express.logger());

 app.get('/', function(request, response) {
     var fs = require('fs');
     var buffer = new Buffer();
     response.send(buffer.toString('utc-8', fs.readFileSync("index.html")));
 });

 var port = process.env.PORT || 5000;
 app.listen(port, function() {
 console.log("Listening on " + port);
 });
Problem courtesy of: Tom Hammond

Solution

When using fs.readFileSync() without specifying any options, the return value will already be a Buffer, so you shouldn't have to create another.

Buffer.isBuffer(fs.readFileSync('index.html'));            // true
typeof fs.readFileSync('index.html', 'utf8') === 'string'; // true

And, res.send() can handle being given a Buffer. It'll actually convert the String back to a Buffer, anyways.

var fs = require('fs');
response.send(fs.readFileSync('index.html'));

You may also want to set a Content-Type so the browser knows it's HTML:

var fs = require('fs');
response.setHeader('Content-Type', 'text/html');
response.send(fs.readFileSync('index.html'));

Or, you can also use Express' res.sendfile(), which will manage both parts for you:

app.get('/', function (request, response) {
    response.sendfile('index.html');
});

Though, if the error you're getting mentions ENOENT, you may need to affix the path.

fs paths will be relative to the current working directory, which may not be what you expect.

response.sendfile(__dirname + '/index.html');
Solution courtesy of: Jonathan Lonowski

Discussion

buffer.toString('utc-8', ... – typo, should be utf-8. But do consider Jonathan’s answer anyway.

Discussion courtesy of: Stefan Paletta

This recipe can be found in it's original form on Stack Over Flow.