async recursive treewalk walks directory tree starting in path - uses asyncbuilder to preserve name-based ordering returns cb(err,tree) where tree[] = array of names (for files) or arrays (for directories)
427485
function treewalk(path, prefix, depth, cb) {

      function sort(entry) { return self.sortEntry(entry.name + (entry.type === 'dir' ? '/' : '')); }

      self.readdir(path, function(err, list) { if (err) return cb(err);
        var ab = asyncbuilder(cb);

        // first normalize names to fix decomposed unicode e.g. from OSX-HFS
        u.each(list, function(entry) { entry.name = normalize(entry.name); });

        u.each(u.sortBy(list, sort), function(entry) {
          var pathname = u.join(path, entry.name);
          var pname = u.join(prefix, entry.name);
          if (self.exclude(entry)) return;
          if (entry.type === 'dir') {
            if (depth >= self.depth) return;
            return treewalk(pathname, pname, depth + 1, ab.asyncAppend()); // recurse
          }
          if (self.mm && !self.mm.match(pname.slice(1))) return; // failed minimatch glob test
          if (entry.type === 'file') {
            var listEntry = { filepath:pname };
            if (entry.sha) { listEntry.sha = entry.sha; }
            if (entry.hash) { listEntry.hash = entry.hash; }
            return ab.append(listEntry);
          }
        });

        ab.complete();
      });
    }
970734
function fsReaddir(path, cb) {
    if (path === '/') return cb(new Error('Reading filesystem at / is disallowed to prevent mistakes.'));
    fs.readdir(path, function(err, dir) { if (err) return cb(err);
      var ab = asyncbuilder(cb);
      u.each(dir, function(name) {
        var push = ab.asyncAppend();
        fs.stat(u.join(path, name), function(err, stats) {
          var entry = !err && { name:name, type:(stats.isDirectory() ? 'dir' : stats.isFile() ? 'file' : 'other') };
          push(err, entry);
        });
      });
      ab.complete();
    });
  }
997946
function findSync(dir, callback) {
	var rootStat = fs.statSync(dir);
	if (!rootStat.isDirectory()) {
		if (callback) callback(dir, rootStat);
		return [dir];
	}

	return fs.readdirSync(dir).reduce(function(files, file) {
		var p = path.join(dir, file),
			stat = fs.statSync(p);
		if (callback) callback(p, stat);
		files.push(p);

		if (stat.isDirectory()) {
			files.push.apply(files, findSync(p, callback));
		}

		return files;
	}, []);
}
458573
function Walker () {
  var self = this;

  var walkSync = function (dir, trace, callback) {
    fs.readdirSync(dir).forEach(function (name) {
      var file = path.join(dir, name)
        , stat = fs.lstatSync(file)
        , isDir = stat.isDirectory()
        , _trace = trace;
      try {
        callback(name, file, isDir, function () {
          return _trace.slice(0);
        });
      }
      finally {
        _trace = null;
      }
      if (isDir) {
        trace.push(name);
        try {
          walkSync(file, trace, callback);
        }
        finally {
          trace.pop();
        }
      }
    });
  };

  /**
   * Traverse the directory synchronously.
   *
   * Parameters
   * - dir: A directory to traverse
   * - callback: A function to be called for each file recursively
   *
   * Returns: The list of information of files contained in 'dir'
   */
  self.walkSync = function (dir, callback) {
    if (typeof callback != 'function') {
      throw new Error("'callback' is not a function.");
    }
    walkSync(dir, [], callback);
  };
}
760325
def walk_tree(start, attr):
    
    path = [start]
    for child in path:
        yield child
        idx = path.index(child)
        for grandchild in reversed(getattr(child, attr)):
            path.insert(idx + 1, grandchild)
16720
function(treeRoot) {
      var stat = fs.statSync(treeRoot);
      if (stat.isDirectory()) {
        return buildTree(treeRoot);
      } else {
        throw new Error("path: " + treeRoot + " is not a directory");
      }
    }
905629
private LinkedList<T> computeRecursiveTraversal(T node, NodePath<T> nodePath) {
    try {


      LinkedList<T> imports = new LinkedList<>();
      Set<T> alreadyIncludedImports = new HashSet<>();

      for (T neighbor : this.traversalFunction.apply(node)) {
        nodePath.appendNode(neighbor);
        addSubtraversal(neighbor, imports, alreadyIncludedImports, nodePath);
        nodePath.popTail();
      }

      return imports;
    } catch (ExecutionException ee) {
      throw new RuntimeException(ee);
    }
  }
1280868
async function buildPathsObject(files) {
  return Promise.all(
    files.map(async filepath => {
      const name = path.basename(filepath, '.svg');
      const svg = fs.readFileSync(filepath, 'utf-8');
      const pathStrings = await svgo.optimize(svg, { path: filepath })
        .then(({ data }) => data.match(/ d="[^"]+"/g) || [])
        .then(paths => paths.map(s => s.slice(3)));
      return `"${name}": [${pathStrings.join(',\n')}]`;
    }),
  );
}
867616
def walk(self, walk_folders=False, walk_files=False):
        

        if not walk_files and not walk_folders:
            return

        for root, _, a_files in os.walk(self.folder.path, followlinks=True):
            folder = Folder(root)
            if walk_folders:
                yield folder
            if walk_files:
                for a_file in a_files:
                    if (not self.pattern or fnmatch.fnmatch(a_file,
                                                            self.pattern)):
                        yield File(folder.child(a_file))
350831
function mkdirSyncRecursive(root, chunks, mode) {

  var chunk = chunks.shift();
  if (!chunk) {
    return;
  }
  var root = path.join(root, chunk);

  if (fs.existsSync(root) === true) { // already done
    return mkdirSyncRecursive(root, chunks, mode);
  }
  var err = fs.mkdirSync(root, mode);
  return err ? err : mkdirSyncRecursive(root, chunks, mode); // let's magic
}
907052
function mkdir(dirPath, callback) {
  // Credits: https://github.com/substack/node-mkdirp

  // Recursively go through the parents.
  const recurse = () => {
    mkdir(path.dirname(dirPath), (error) => {
      if (error) {
        async.nextTick(callback, error);
        return;
      }

      // Try again.
      mkdir(dirPath, callback);
    });
  };

  // Plan B for when things seem to go wrong.
  const fallBack = () => {
    fs.stat(dirPath, (error, stat) => {
      if (error || !stat.isDirectory()) {
        async.nextTick(
          callback,
          new Error(`${dirPath}: Could not create the directory`)
        );
        return;
      }

      async.nextTick(callback, null);
    });
  };

  fs.mkdir(dirPath, (error) => {
    if (!error) {
      async.nextTick(callback, null);
      return;
    }

    switch (error.code) {
      case 'ENOENT':
        recurse();
        break;
      default:
        fallBack();
        break;
    }
  });
}
175899
def _walk(recursion):
    """"""
    try:
        from scandir import walk as walk_function
    except ImportError:
        from os import walk as walk_function

    if recursion:
        walk = partial(walk_function)
    else:
        def walk(path):  # pylint: disable=C0111
            try:
                yield next(walk_function(path))
            except NameError:
                yield walk_function(path)
    return walk
802499
function mkdirp(con, p, callback) {
  p = path.normalize(p);
  var dirs = p.split('/').slice(1); // remove empty string at the start.

  // console.log('dirs', dirs);

  var tasks = [];
  dirs.forEach(function(dir, i) {
    var subpath = '/' + dirs.slice(0, i).join('/') + '/' + dir;
    subpath = path.normalize(subpath); // remove extra `/` in first iteration
    tasks.push(async.apply(create, con, subpath));
  });
  async.waterfall(tasks, function(err, results) {
    if(err) return callback(err);
    // succeeded!
    return callback(null, true);
  });
}
591660
function rmdirSyncRecursive(root, chunks) {

  var chunk = chunks.pop();
  if (!chunk) {
    return;
  }
  var pathname = path.join(root, '..'); // backtrack

  if (fs.existsSync(root) === false) { // already done
    return rmdirSyncRecursive(root, chunks);
  }
  var err = fs.rmdirSync(root);
  return err ? err : rmdirSyncRecursive(pathname, chunks); // let's magic
}
824286
function walk(path, floor, handleFile) {
	handleFile(path, floor);
	floor++;
	fs.readdir(path, function(err, files) {
		if (err) {
			console.log('read dir error');
		} else {
			files.forEach(function(item) {
				var tmpPath = path + '/' + item;
				fs.stat(tmpPath, function(err1, stats) {
					if (err1) {
						console.log('stat error');
					} else {
						if (stats.isDirectory()) {
							walk(tmpPath, floor, handleFile);
						} else {
							handleFile(tmpPath, floor);
						}
					}
				})
			});

		}
	});
}
940443
def walk(self, path = None, topdown=True):
        

        if path is None:
            path = self.root

        root = self.find(path)

        if not root.isdir():
            raise ValueError("can only walk storage types")

        if not root.child_id:
            return

        if topdown:
            storage_items = []
            stream_items = []

            for item in self.listdir(root):
                if item.isdir():
                    storage_items.append(item)
                else:
                    stream_items.append(item)

            yield root, storage_items, stream_items

            for item in storage_items:
                for root, storage_items, stream_items in self.walk(item):
                    yield root, storage_items, stream_items
        else:

            def topdown_visit_node(root):
                storage_items = []
                stream_items = []
                for item in self.listdir(root):
                    if item.isdir():
                        for sub_root, sub_storage, sub_stream in topdown_visit_node(item):
                            yield sub_root, sub_storage, sub_stream

                        storage_items.append(item)
                    else:
                        stream_items.append(item)

                yield root, storage_items, stream_items

            for root_item, storage, stream in topdown_visit_node(root):
                yield root_item, storage, stream
734971
def walk(pathobj, topdown=True):
    
    dirs, nondirs = [], []
    for child in pathobj:
        relpath = str(child.relative_to(str(pathobj)))
        if relpath.startswith('/'):
            relpath = relpath[1:]
        if relpath.endswith('/'):
            relpath = relpath[:-1]
        if child.is_dir():
            dirs.append(relpath)
        else:
            nondirs.append(relpath)
    if topdown:
        yield pathobj, dirs, nondirs
    for dir in dirs:
        for result in walk(pathobj / dir):
            yield result
    if not topdown:
        yield pathobj, dirs, nondirs