Return a couchDB result set to use it in a template

I want to find all users in a nodejs app and display them.

app.js

var express = require('express');
var hbs     = require('hbs');

var app = express();    
var user = require('./user');

app.set('view engine', 'html');
app.engine('html', hbs.__express);

app.use(express.static('public'));
app.use(express.bodyParser());

app.get('/', function(req, res) {
  res.render('user/index', {
      title: "User overview", 
      users: user.all()
    }
  );
});

user.js

var http = require('http');

var options = {
  host: 'localhost',
  port: 5984,
  path: '/user/_all_docs?include_docs=true',
  headers : {
    'accept': 'application/json'
  }
};

exports.all = function() { 
  // Store them ?
  var entries = [];

  var db_req = http.request(options, function(db_res) {
    db_res.setEncoding('utf8');

    db_res.on('data', function(data){
      entries.push(data);
    });

  });

  db_req.end();

  // Return entries somehow?
}

I understand that nodejs is doing parallel requests, so simply returning the entries list is not possible. But what function or callback do I need to use after db_req.end() to make sure the entries is not an empty list?

There are two things wrong with your code.

First of all http.request and the subsequent response are asynchronous methods. So you cannot return anything from them. Technically you can but there is no way you will get a handle to the returned value. That is why we have callbacks. So instead accept a callback and call it.

Secondly your db_res will emit data event only when it receives next chunk of response and the chunks are not separate pieces of data, they are just text. So rather than pushing each inside an array, concatenate them as a string, deserialize it, and then return. Like so

exports.all = function(callback) { 
  // Store them ?
  var entries = "";

  var db_req = http.request(options, function(db_res) {
    db_res.setEncoding('utf8');

    db_res.on('data', function(data){
      entries = entries + data;
    });

    db_res.on('end', function(){
       callback(JSON.parse(data));
    });

  });

  db_req.end();

  // Return entries somehow?
}