make a more synchronous version possible

This commit is contained in:
AJ ONeal 2013-06-22 22:58:07 -07:00
父節點 ec07897228
當前提交 dad2e70092

查看文件

@ -24,53 +24,97 @@ Usage
Both Asynchronous and Synchronous versions are provided. Both Asynchronous and Synchronous versions are provided.
The Synchronous version still uses callbacks, so it is safe to use with other Asynchronous functions and will still work as expected. var walk = require('walk')
, fs = require('fs')
, options
, walker
;
var walk = require('walk'), options = {
fs = require('fs'),
options,
walker;
options = {
followLinks: false, followLinks: false,
}; };
walker = walk.walk("/tmp", options); walker = walk.walk("/tmp", options);
// OR // OR
// walker = walk.walkSync("/tmp", options); // walker = walk.walkSync("/tmp", options);
walker.on("names", function (root, nodeNamesArray) { walker.on("names", function (root, nodeNamesArray) {
nodeNames.sort(function (a, b) { nodeNames.sort(function (a, b) {
if (a > b) return 1; if (a > b) return 1;
if (a < b) return -1; if (a < b) return -1;
return 0; return 0;
}); });
}); });
walker.on("directories", function (root, dirStatsArray, next) { walker.on("directories", function (root, dirStatsArray, next) {
// dirStatsArray is an array of `stat` objects with the additional attributes // dirStatsArray is an array of `stat` objects with the additional attributes
// * type // * type
// * error // * error
// * name // * name
next(); next();
}); });
walker.on("file", function (root, fileStats, next) { walker.on("file", function (root, fileStats, next) {
fs.readFile(fileStats.name, function () { fs.readFile(fileStats.name, function () {
// doStuff // doStuff
next(); next();
}); });
}); });
walker.on("errors", function (root, nodeStatsArray, next) { walker.on("errors", function (root, nodeStatsArray, next) {
next();
});
walker.on("end", function () {
console.log("all done");
});
```
### Async
The Synchronous version can operate without a callback if the event handlers are passed in
```javascript
var walk = require('walk')
, fs = require('fs')
, options
, walker
;
options = {
listeners: {
names: function (root, nodeNamesArray) {
nodeNames.sort(function (a, b) {
if (a > b) return 1;
if (a < b) return -1;
return 0;
});
}
, directories: function (root, dirStatsArray, next) {
// dirStatsArray is an array of `stat` objects with the additional attributes
// * type
// * error
// * name
next();
}
, file: function (root, fileStats, next) {
fs.readFile(fileStats.name, function () {
// doStuff
next(); next();
}); });
}
, errors: function (root, nodeStatsArray, next) {
next();
}
}
};
walker.on("end", function () { walker = walk.walkSync("/tmp", options);
console.log("all done");
}); console.log("all done");
```
API API
==== ====