Tom Hammond
Tom Hammond

Reputation: 6090

Reading HTML in Node.js

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);
 });

Upvotes: 0

Views: 1317

Answers (2)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123563

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');

Upvotes: 2

Stefan Paletta
Stefan Paletta

Reputation: 378

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

Upvotes: 1

Related Questions