Reading all files in a directory, store them in objects, and send the object

I do not know if this is possible, but here goes. And working with callbacks makes it even more difficult.

I have a directory with html files that I want to send back to the client in Object chunks with node.js and socket.io.

All my files are in /tmpl

So socket needs to read all the files in /tmpl.

for each file it has to store the data in an object with the filename as the key, and the content as the value.

  var data;
  // this is wrong because it has to loop trough all files.
  fs.readFile(__dirname + '/tmpl/filename.html', 'utf8', function(err, html){
      if(err) throw err;
      //filename must be without .html at the end
      data['filename'] = html;
  });
  socket.emit('init', {data: data});

The final callback is also wrong. It has to be called when all the files in the directory are done.

But I do not know how to create the code, anyone know if this is possibel?

Try something like this:

var fs=require('fs');

var dir='./tmpl/';
var data={};

fs.readdir(dir,function(err,files){
    if (err) throw err;
    var c=0;
    files.forEach(function(file){
        c++;
        fs.readFile(dir+file,'utf-8',function(err,html){
            if (err) throw err;
            data[file]=html;
            if (0===--c) {
                console.log(data);  //socket.emit('init', {data: data});
            }
        });
    });
});