views:

242

answers:

1

Using Express (for node.js) How do I write a response after a callback?

The following is a minimal example. posix.cat is a function that returns a promise, up does something to the result, and I want to send that as the response.

require.paths.unshift('lib');
require('express');
var posix = require('posix');

get('/', function () {
    function up(s) {
        return s.toUpperCase();
    }
    return posix.cat('/etc/motd').addCallback(up);
});

run(3001);

The client never gets a response.

I've also tried variations on this:

get('/2', function () {
    var myRequest = this;
    function up(s) {
        myRequest.respond(s.toUpperCase());
    }
    return posix.cat('/etc/motd').addCallback(up);
});

but that tends to crash everything:

[object Object].emitSuccess (node.js:283:15)
[object Object].<anonymous> (node.js:695:21)
[object Object].emitSuccess (node.js:283:15)
node.js:552:29
node.js:1027:1
node.js:1031:1
A: 

According to this, the problem with approach #2 that respond was called before a status code was set.

This works:

get('/2', function () {
    var myRequest = this;
    function up(s) {
        myRequest.halt(200, s.toUpperCase());
    }
    return posix.cat('/etc/motd').addCallback(up);
});
keturn