I'm started learning JavaScript promises, but I can't understand how apply, for example, Q functions to Node.js callback functions.
In similar question is recommended to use Q.denodeify(), but it works well for fs.readFile() and don't works for fs.exists().
This is a simple functions that returns list of files and their sizes in directory:
function openDir(path, callback) {
path = __dirname + path;
fs.exists(path, function (exists) {
if (exists) {
fs.readdir(path, function (err, files) {
if (err) {
throw err;
}
var filesCounter = 0,
filesTotal = files.length,
result = [];
files.forEach(function (filename, index) {
fs.stat(path + filename, function (err, stats) {
if (err) {
throw err;
}
result[index] = {};
result[index].name = filename;
result[index].size = stats.size;
if (++filesCounter === filesTotal) {
callback(result);
}
});
});
});
}
});
}
http.createServer(function (req, res) {
openDir('/', function (data) {
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8'
});
res.end(JSON.stringify(data));
});
}).listen(1337, '127.0.0.1');
How write this code using promises (with Q or other library)?