Debian Codegraph @

node/readdirp/README.md

raw
1 # readdirp [![Weekly downloads](https://img.shields.io/npm/dw/readdirp.svg)](https://github.com/paulmillr/readdirp)
2
3 Recursive version of fs.readdir. Exposes a **stream API** (with small RAM & CPU footprint) and a **promise API**.
4
5 Faster than built-in `fs.readdir recursive: true`, and uses less RAM.
6
7 ```sh
8 npm install readdirp
9 jsr add jsr:@paulmillr/readdirp
10 ```
11
12 ```javascript
13 // Use streams to achieve small RAM & CPU footprint.
14 // 1) Streams example with for-await.
15 import readdirp from 'readdirp';
16 for await (const entry of readdirp('.')) {
17 const {path} = entry;
18 console.log(`${JSON.stringify({path})}`);
19 }
20
21 // 2) Streams example, non for-await.
22 // Print out all JS files along with their size within the current folder & subfolders.
23 import readdirp from 'readdirp';
24 readdirp('.', {alwaysStat: true, fileFilter: (f) => f.basename.endsWith('.js')})
25 .on('data', (entry) => {
26 const {path, stats: {size}} = entry;
27 console.log(`${JSON.stringify({path, size})}`);
28 })
29 // Optionally call stream.destroy() in `warn()` in order to abort and cause 'close' to be emitted
30 .on('warn', error => console.error('non-fatal error', error))
31 .on('error', error => console.error('fatal error', error))
32 .on('end', () => console.log('done'));
33
34 // 3) Promise example. More RAM and CPU than streams / for-await.
35 import { readdirpPromise } from 'readdirp';
36 const files = await readdirpPromise('.');
37 console.log(files.map(file => file.path));
38
39 // Other options.
40 import readdirp from 'readdirp';
41 readdirp('test', {
42 fileFilter: (f) => f.basename.endsWith('.js'),
43 directoryFilter: (d) => d.basename !== '.git',
44 // directoryFilter: (di) => di.basename.length === 9
45 type: 'files_directories',
46 depth: 1
47 });
48 ```
49
50 ## API
51
52 `const stream = readdirp(root[, options])` — **Stream API**
53
54 - Reads given root recursively and returns a `stream` of [entry infos](#entryinfo)
55 - Optionally can be used like `for await (const entry of stream)` with node.js 10+ (`asyncIterator`).
56 - `on('data', (entry) => {})` [entry info](#entryinfo) for every file / dir.
57 - `on('warn', (error) => {})` non-fatal `Error` that prevents a file / dir from being processed. Example: inaccessible to the user.
58 - `on('error', (error) => {})` fatal `Error` which also ends the stream. Example: illegal options where passed.
59 - `on('end')` — we are done. Called when all entries were found and no more will be emitted.
60 - `on('close')` — stream is destroyed via `stream.destroy()`.
61 Could be useful if you want to manually abort even on a non fatal error.
62 At that point the stream is no longer `readable` and no more entries, warning or errors are emitted
63 - To learn more about streams, consult the very detailed [nodejs streams documentation](https://nodejs.org/api/stream.html)
64 or the [stream-handbook](https://github.com/substack/stream-handbook)
65
66 `const entries = await readdirp.promise(root[, options])` — **Promise API**. Returns a list of [entry infos](#entryinfo).
67
68 First argument is awalys `root`, path in which to start reading and recursing into subdirectories.
69
70 ### options
71
72 - `fileFilter`: filter to include or exclude files
73 - **Function**: a function that takes an entry info as a parameter and returns true to include or false to exclude the entry
74 - `directoryFilter`: filter to include/exclude directories found and to recurse into. Directories that do not pass a filter will not be recursed into.
75 - `depth: 5`: depth at which to stop recursing even if more subdirectories are found
76 - `type: 'files'`: determines if data events on the stream should be emitted for `'files'` (default), `'directories'`, `'files_directories'`, or `'all'`. Setting to `'all'` will also include entries for other types of file descriptors like character devices, unix sockets and named pipes.
77 - `alwaysStat: false`: always return `stats` property for every file. Default is `false`, readdirp will return `Dirent` entries. Setting it to `true` can double readdir execution time - use it only when you need file `size`, `mtime` etc. Cannot be enabled on node <10.10.0.
78 - `lstat: false`: include symlink entries in the stream along with files. When `true`, `fs.lstat` would be used instead of `fs.stat`
79
80 ### `EntryInfo`
81
82 Has the following properties:
83
84 - `path: 'assets/javascripts/react.js'`: path to the file/directory (relative to given root)
85 - `fullPath: '/Users/dev/projects/app/assets/javascripts/react.js'`: full path to the file/directory found
86 - `basename: 'react.js'`: name of the file/directory
87 - `dirent: fs.Dirent`: built-in [dir entry object](https://nodejs.org/api/fs.html#fs_class_fs_dirent) - only with `alwaysStat: false`
88 - `stats: fs.Stats`: built in [stat object](https://nodejs.org/api/fs.html#fs_class_fs_stats) - only with `alwaysStat: true`
89
90 ## Changelog
91
92 - 4.0 (Aug 25, 2024) rewritten in typescript, producing hybrid common.js / esm module.
93 - Remove glob support and all dependencies
94 - Make sure you're using `let {readdirp} = require('readdirp')` in common.js
95 - 3.5 (Oct 13, 2020) disallows recursive directory-based symlinks.
96 Before, it could have entered infinite loop.
97 - 3.4 (Mar 19, 2020) adds support for directory-based symlinks.
98 - 3.3 (Dec 6, 2019) stabilizes RAM consumption and enables perf management with `highWaterMark` option. Fixes race conditions related to `for-await` looping.
99 - 3.2 (Oct 14, 2019) improves performance by 250% and makes streams implementation more idiomatic.
100 - 3.1 (Jul 7, 2019) brings `bigint` support to `stat` output on Windows. This is backwards-incompatible for some cases. Be careful. It you use it incorrectly, you'll see "TypeError: Cannot mix BigInt and other types, use explicit conversions".
101 - 3.0 brings huge performance improvements and stream backpressure support.
102 - Upgrading 2.x to 3.x:
103 - Signature changed from `readdirp(options)` to `readdirp(root, options)`
104 - Replaced callback API with promise API.
105 - Renamed `entryType` option to `type`
106 - Renamed `entryType: 'both'` to `'files_directories'`
107 - `EntryInfo`
108 - Renamed `stat` to `stats`
109 - Emitted only when `alwaysStat: true`
110 - `dirent` is emitted instead of `stats` by default with `alwaysStat: false`
111 - Renamed `name` to `basename`
112 - Removed `parentDir` and `fullParentDir` properties
113 - Supported node.js versions:
114 - 4.x: node 14+
115 - 3.x: node 8+
116 - 2.x: node 0.6+
117
118 ## License
119
120 Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (<https://paulmillr.com>)
121
122 MIT License, see [LICENSE](LICENSE) file.