nodejs send html file to client

user3044147 picture user3044147 · Dec 3, 2013 · Viewed 133.4k times · Source

I use this function to send html file to client, but in client I get nothing (blank page) without error. Something I wrong?, please help?

var express = require('express'); 
var fs = require('fs');
var app = express();
app.set('view engine', 'jade');
app.engine('jade', require('jade').__express); 
    app.get('/test', function(req, res) {
            fs.readFile(__dirname + '/views/test.html', 'utf8', function(err, text){
                res.send(text);
            });
var port = process.env.PORT || 80;
var server = app.listen(port);
console.log('Express app started on port ' + port);

My test.html file

<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <style something here </style>
      <title>Test</title>
      <script src="..."></script>
   </head>
<body>
    <div> Somthing here </div>

    <script type="text/javascript">
        //something here
    </script>
</body></html>

Answer

Tim Brown picture Tim Brown · Dec 3, 2013

Try your code like this:

var app = express();
app.get('/test', function(req, res) {
    res.sendFile('views/test.html', {root: __dirname })
});
  1. Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.

  2. You don't need the app.engine line, as that is handled internally by express.