Reputation: 437
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
Upvotes: 9
Views: 9517
Reputation: 21
i had same problem with download(file), now it works perfecto
server.get('/download', (req, res) => {
res.download('./text.txt', 'text.txt', function (err) {
if (err) {
res.status(404)
res.end();
console.log('download failed');
console.error(err);
} else {
console.log('downloaded seccefully');
res.end();
}
})
});
Upvotes: 2
Reputation: 11677
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();
});
});
Upvotes: 11