Calling next step with parameters in Node.js Step module
I've just started using Step, and I'm trying to get the 开发者_StackOverflow中文版stat
information of all files in a directory.
However as I'm calling fs.stat
in the second step, I still need the full path. How can I pass it to the next method? I've tried this(directory)
but it didn't work as I expected.
var getFiles = step.fn(
function readDir(directory) {
var p = path.join(__dirname, directory);
fs.readdir(p, this); // *** How do I pass 'directory' to the next method?
},
function readFiles(err, results, directory) {
if (err) throw err;
// Create a new group
var group = this.group();
results.forEach(function (filename) {
console.log(filename);
var p = path.join(__dirname, directory, filename);
// fs.stat requires a full path
fs.stat(p, group()); // Could be this.parallel() ??
});
}
);
// later...
var files = getFiles('data');
As I understand it, readDir
gets called once, then readFiles
gets called, but all in series as fs.readdir
's callback just gets called once, with an array of files.
You could use a variable scoped outside getFiles (hacky), or you could also use a closure.
Personally, I would switch from step to async (https://github.com/caolan/async). The waterfall method provided in async is what you're really looking for. Async has the same functionality as step and more.
fs.readdir(p, (function(err, files) {
this(err, files, directory);
}).bind(this));
this
is just a function. You can call it explicitly.
You could always use Q-Oper8:
https://github.com/robtweed/Q-Oper8
Then you could safely use the sync fs methods which might make it easier to do what you're wanting to do.
精彩评论