On a simple node server running Express.js (3.8.6). I am attempting to use sendFile
to send a simple HTML file to the client.
What am I missing?
Code
//server.js
var http = require("http");
var express = require("express");
var app = express();
var server = http.createServer(app);
var path = require('path');
//Server views folder as a static in case that's required for sendFile(??)
app.use('/views', express.static('views'));
var myPath = path.resolve("./views/lobbyView.html");
// File Testing
//--------------------------
//This works fine and dumps the file to my console window
var fs = require('fs');
fs.readFile(myPath, 'utf8', function (err,data) {
console.log (err ? err : data);
});
// Send File Testing
//--------------------------
//This writes nothing to the client and throws the ECONNABORTED error
app.get('/', function(req, res){
res.sendFile(myPath, null, function(err){
console.log(err);
});
res.end();
});
Project Setup
You're prematurely calling res.end()
. Remember, that Node.js is asynchronous, thus what you're actually doing is cancelling your sendFile
before it completes. Change it to :
app.get('/', function(req, res){
res.sendFile(myPath, null, function(err){
console.log(err);
res.end();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With