UNPKG

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