In Meteor
, I'm writing a method that will have to check a certain path's subdirectories for new files.
I first would like to just list the subdirectories within Meteor
after which I child_process.exec
a simple bash script that lists files added since the last time it executed.
I'm having some issues getting the directory discovery to be async (Error: Can't wait without a fiber
). I've written a synchronous version but having both fs.readdir
and fs.stat
in stead of their synchronous alternatives allows me to catch errors.
Here's the code:
function listDirs(dir, isDir){
var future1 = new Future();fs.readdir(dir, function(err, files){
if (err)
throw new Meteor.error(500, "Error listing files", err);
var dirs = _.map(files, function(file){
var future2 = new Future();
var resolve2 = future2.resolver();
fs.stat(dir+file, function(err, stats){
if (err)
throw new Meteor.error(500, "Error statting files", err);
if (stats.isDirectory() == isDir && file.charAt(0) !== '.')
resolve2(err, file);
});
return future2;
});
Future.wait(dirs);
//var result = _.invoke(dirs, 'get');
future1['return'](_.compact(dirs));
});
return future1.wait();
}
The error Error: Can't wait without a fiber
has to do with future2
.
When I comment out Future.wait(dirs)
the server doesn't crash anymore, but that's about as far as I got in trying to solve this. :/
Another _.map
function I use in another part of the method works fine with futures. (see also https://gist.github.com/possibilities/3443021 where I found my inspiration)
Wrap your callback into Meteor.bindEnvironment
, example:
fs.readdir(dir, Meteor.bindEnvironment(function (err, res) {
if (err) future.throw(err);
future.return(res);
}, function (err) { console.log("couldn't wrap the callback"); });
Meteor.bindEnvironment
does a lot of things and one of them is to make sure callback is running in a Fiber.
Another thing that could be helpful is var funcSync = Meteor._wrapAsync(func)
which utilizes futures and allows use to call a function in synchronous style (but it is still async).
Watch these videos on evented mind if you want to know more: https://www.eventedmind.com/posts/meteor-dynamic-scoping-with-environment-variables https://www.eventedmind.com/posts/meteor-what-is-meteor-bindenvironment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With