Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js sendFile returning ECONNABORTED

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.

  • The path is shown to be good from the file read.
  • The cache is disabled on the browser.
  • The code shown is the server.js file and is run from node directly

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

Project Setup

like image 465
maulkye Avatar asked Apr 30 '16 00:04

maulkye


1 Answers

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();
  });
});
like image 147
Yuri Zarubin Avatar answered Sep 24 '22 02:09

Yuri Zarubin