1252748 1252748 - 4 months ago 10
Node.js Question

Express with Q deferred not responding to requests

I'm trying to use a node backend with my angular script using Q to promise-fy an fs method. Using the normal callback method works, however here, nothing is returned to Angular. Nothing is printed in the console, and no error is returned in the console or in the terminal where node is running. What have I missed?

var express = require('express');
var app = express();
var router = express.Router();
var FS = require('fs');
var Q = require('q');

app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use('/dist', express.static(__dirname + '/dist'));

app.get('/', function(req, res) {
res.sendfile('./index.html');
});

app.get('/test', function(req, res){
// res.send('asdf')
var deferred = Q.defer();
FS.readFile("gulpfile.js", "utf-8", function (error, text) {
console.log('error', error);
console.log('in read file')
if (error) {
deferred.reject(new Error(error));
} else {
res.send(text);
deferred.resolve(text);
}
});
return deferred.promise;
});

app.listen(5000);

Answer

Express does not support promises out of the box. Returning a promise from a handler means nothing to it. You still have to call res.send explicitly (although there are modules such a express-promise to ease this).

This is what your code should look like:

app.get('/test', function(req, res){
    var promise = Q.ninvoke(FS, "readFile", "gulpfile.js", "utf-8");
    promise.then(function (text) {
        res.status(200).send(text);
    }, function(error) {
        console.error(error);
        res.status(500).send("oops");
    });
});