This repository has been archived by the owner on Oct 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
fs-readdir-rec-gen.js
72 lines (66 loc) · 2.75 KB
/
fs-readdir-rec-gen.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* Copyright (C) 2017 Orange
*
* This software is distributed under the terms and conditions of the 'MIT'
* license which can be found in the file 'LICENSE.txt' in this package
* distribution or at 'http://spdx.org/licenses/MIT'.
*
* @author Nicolas MOTEAU <nicolas.moteau@orange.com>
*/
var fs = require('fs');
var path = require('path');
/**
* Get a generator for file names contained in a directory an subdirectories.
* The file names contain their relative path.
* @param dir {String} - the directory where to look for files.
* @param options {String|Object} - optional, options passed NodeJs File System API (see https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback).
* @param filter {Function} - optional, a function to filter on file names. Defaults to no filter.
* @param recursive {Boolean} - optional, whether to search in sub directories. Defaults to true.
* @return a generator for files names
*/
function readdirRecGen(dir, options = undefined, filter = undefined, recursive = true) {
/* Manage optional arguments only once in recursive calls*/
if (typeof options !== 'string' && typeof options !== 'object') {
// Shift arguments
recursive = filter !== undefined ? filter : true;
filter = options;
options = undefined;
}
if (typeof filter !== 'function') {
// Shift arguments
recursive = filter !== undefined ? filter : true;
filter = undefined;
}
// Check directory existence
fs.statSync(dir);
return _readdirRecGen(dir, options, filter, recursive);
}
/**
* Get a generator for file names contained in a directory an subdirectories.
* The file names contain their relative path.
* @param dir {String} - the directory where to look for files
* @param options {String|Object} - options passed NodeJs File System API (see https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback)
* @param filter {Function} - a function to filter on file names. If undefined, defaults to no filter.
* @param recursive {Boolean} - whether to search in sub directories.
* @return a generator for files names
* @private
*/
function* _readdirRecGen(dir, options, filter, recursive) {
for (let file of fs.readdirSync(dir, options)) {
var relativePathFileName = path.join(dir, file);
if (fs.statSync(relativePathFileName).isDirectory()) {
if (recursive) {
yield* _readdirRecGen(relativePathFileName, options, filter, recursive);
}
} else {
if (filter) {
if (filter(relativePathFileName)) {
yield relativePathFileName;
}
} else {
yield relativePathFileName;
}
}
}
}
module.exports = readdirRecGen;