UNPKG

1.54 kBJavaScriptView Raw
1var path = require('path');
2var common = require('./common');
3var _ls = require('./ls');
4
5common.register('find', _find, {});
6
7//@
8//@ ### find(path [, path ...])
9//@ ### find(path_array)
10//@ Examples:
11//@
12//@ ```javascript
13//@ find('src', 'lib');
14//@ find(['src', 'lib']); // same as above
15//@ find('.').filter(function(file) { return file.match(/\.js$/); });
16//@ ```
17//@
18//@ Returns array of all files (however deep) in the given paths.
19//@
20//@ The main difference from `ls('-R', path)` is that the resulting file names
21//@ include the base directories, e.g. `lib/resources/file1` instead of just `file1`.
22function _find(options, paths) {
23 if (!paths) {
24 common.error('no path specified');
25 } else if (typeof paths === 'string') {
26 paths = [].slice.call(arguments, 1);
27 }
28
29 var list = [];
30
31 function pushFile(file) {
32 if (process.platform === 'win32') {
33 file = file.replace(/\\/g, '/');
34 }
35 list.push(file);
36 }
37
38 // why not simply do ls('-R', paths)? because the output wouldn't give the base dirs
39 // to get the base dir in the output, we need instead ls('-R', 'dir/*') for every directory
40
41 paths.forEach(function (file) {
42 var stat;
43 try {
44 stat = common.statFollowLinks(file);
45 } catch (e) {
46 common.error('no such file or directory: ' + file);
47 }
48
49 pushFile(file);
50
51 if (stat.isDirectory()) {
52 _ls({ recursive: true, all: true }, file).forEach(function (subfile) {
53 pushFile(path.join(file, subfile));
54 });
55 }
56 });
57
58 return list;
59}
60module.exports = _find;