UNPKG

1.46 kBJavaScriptView Raw
1/*
2* This function was copied with permission from:
3* https://gist.github.com/825583
4*
5* It was then modified to be synchronous
6*/
7var fs = require('fs'),
8 path = require('path');
9
10module.exports = function readDir(start, callback) {
11 // Use lstat to resolve symlink if we are passed a symlink
12 var stat = fs.lstatSync(start),
13 found = {dirs: [], files: []},
14 total = 0,
15 processed = 0,
16 isDir = function isDir(abspath) {
17 var stat = fs.statSync(abspath);
18 if(stat.isDirectory()) {
19 found.dirs.push(abspath);
20 // If we found a directory, recurse!
21 var data = readDir(abspath);
22 found.dirs = found.dirs.concat(data.dirs);
23 found.files = found.files.concat(data.files);
24 if(++processed == total) {
25 return false;
26 }
27 } else {
28 found.files.push(abspath);
29 if(++processed == total) {
30 return false;
31 }
32 }
33 }
34 // Read through all the files in this directory
35 if(stat.isDirectory()) {
36 var files = fs.readdirSync(start);
37 total = files.length;
38 for (var x=0, l=files.length; x<l; x++) {
39 isDir(path.join(start, files[x]));
40 }
41 } else {
42 return callback(new Error("path: " + start + " is not a directory"));
43 }
44 return found;
45};
46