0

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

2 Answers 2

2

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');
Sign up to request clarification or add additional context in comments.

1 Comment

This is great information and was very helpful! I wasn't able to figure out exactly what was wrong - I tried everything you mentioned a bunch of times and it continued to throw the error. Then I tried going back to just doing response.send('Hello World!') and it still threw the error. So I just created a new directory/app and it works!!!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.