You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

122 lines
6.8 KiB

2 years ago
  1. # readdirp [![Weekly downloads](https://img.shields.io/npm/dw/readdirp.svg)](https://github.com/paulmillr/readdirp)
  2. Recursive version of [fs.readdir](https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback). Exposes a **stream API** and a **promise API**.
  3. ```sh
  4. npm install readdirp
  5. ```
  6. ```javascript
  7. const readdirp = require('readdirp');
  8. // Use streams to achieve small RAM & CPU footprint.
  9. // 1) Streams example with for-await.
  10. for await (const entry of readdirp('.')) {
  11. const {path} = entry;
  12. console.log(`${JSON.stringify({path})}`);
  13. }
  14. // 2) Streams example, non for-await.
  15. // Print out all JS files along with their size within the current folder & subfolders.
  16. readdirp('.', {fileFilter: '*.js', alwaysStat: true})
  17. .on('data', (entry) => {
  18. const {path, stats: {size}} = entry;
  19. console.log(`${JSON.stringify({path, size})}`);
  20. })
  21. // Optionally call stream.destroy() in `warn()` in order to abort and cause 'close' to be emitted
  22. .on('warn', error => console.error('non-fatal error', error))
  23. .on('error', error => console.error('fatal error', error))
  24. .on('end', () => console.log('done'));
  25. // 3) Promise example. More RAM and CPU than streams / for-await.
  26. const files = await readdirp.promise('.');
  27. console.log(files.map(file => file.path));
  28. // Other options.
  29. readdirp('test', {
  30. fileFilter: '*.js',
  31. directoryFilter: ['!.git', '!*modules']
  32. // directoryFilter: (di) => di.basename.length === 9
  33. type: 'files_directories',
  34. depth: 1
  35. });
  36. ```
  37. For more examples, check out `examples` directory.
  38. ## API
  39. `const stream = readdirp(root[, options])`**Stream API**
  40. - Reads given root recursively and returns a `stream` of [entry infos](#entryinfo)
  41. - Optionally can be used like `for await (const entry of stream)` with node.js 10+ (`asyncIterator`).
  42. - `on('data', (entry) => {})` [entry info](#entryinfo) for every file / dir.
  43. - `on('warn', (error) => {})` non-fatal `Error` that prevents a file / dir from being processed. Example: inaccessible to the user.
  44. - `on('error', (error) => {})` fatal `Error` which also ends the stream. Example: illegal options where passed.
  45. - `on('end')` — we are done. Called when all entries were found and no more will be emitted.
  46. - `on('close')` — stream is destroyed via `stream.destroy()`.
  47. Could be useful if you want to manually abort even on a non fatal error.
  48. At that point the stream is no longer `readable` and no more entries, warning or errors are emitted
  49. - To learn more about streams, consult the very detailed [nodejs streams documentation](https://nodejs.org/api/stream.html)
  50. or the [stream-handbook](https://github.com/substack/stream-handbook)
  51. `const entries = await readdirp.promise(root[, options])`**Promise API**. Returns a list of [entry infos](#entryinfo).
  52. First argument is awalys `root`, path in which to start reading and recursing into subdirectories.
  53. ### options
  54. - `fileFilter: ["*.js"]`: filter to include or exclude files. A `Function`, Glob string or Array of glob strings.
  55. - **Function**: a function that takes an entry info as a parameter and returns true to include or false to exclude the entry
  56. - **Glob string**: a string (e.g., `*.js`) which is matched using [picomatch](https://github.com/micromatch/picomatch), so go there for more
  57. information. Globstars (`**`) are not supported since specifying a recursive pattern for an already recursive function doesn't make sense. Negated globs (as explained in the minimatch documentation) are allowed, e.g., `!*.txt` matches everything but text files.
  58. - **Array of glob strings**: either need to be all inclusive or all exclusive (negated) patterns otherwise an error is thrown.
  59. `['*.json', '*.js']` includes all JavaScript and Json files.
  60. `['!.git', '!node_modules']` includes all directories except the '.git' and 'node_modules'.
  61. - Directories that do not pass a filter will not be recursed into.
  62. - `directoryFilter: ['!.git']`: filter to include/exclude directories found and to recurse into. Directories that do not pass a filter will not be recursed into.
  63. - `depth: 5`: depth at which to stop recursing even if more subdirectories are found
  64. - `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.
  65. - `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.
  66. - `lstat: false`: include symlink entries in the stream along with files. When `true`, `fs.lstat` would be used instead of `fs.stat`
  67. ### `EntryInfo`
  68. Has the following properties:
  69. - `path: 'assets/javascripts/react.js'`: path to the file/directory (relative to given root)
  70. - `fullPath: '/Users/dev/projects/app/assets/javascripts/react.js'`: full path to the file/directory found
  71. - `basename: 'react.js'`: name of the file/directory
  72. - `dirent: fs.Dirent`: built-in [dir entry object](https://nodejs.org/api/fs.html#fs_class_fs_dirent) - only with `alwaysStat: false`
  73. - `stats: fs.Stats`: built in [stat object](https://nodejs.org/api/fs.html#fs_class_fs_stats) - only with `alwaysStat: true`
  74. ## Changelog
  75. - 3.5 (Oct 13, 2020) disallows recursive directory-based symlinks.
  76. Before, it could have entered infinite loop.
  77. - 3.4 (Mar 19, 2020) adds support for directory-based symlinks.
  78. - 3.3 (Dec 6, 2019) stabilizes RAM consumption and enables perf management with `highWaterMark` option. Fixes race conditions related to `for-await` looping.
  79. - 3.2 (Oct 14, 2019) improves performance by 250% and makes streams implementation more idiomatic.
  80. - 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".
  81. - 3.0 brings huge performance improvements and stream backpressure support.
  82. - Upgrading 2.x to 3.x:
  83. - Signature changed from `readdirp(options)` to `readdirp(root, options)`
  84. - Replaced callback API with promise API.
  85. - Renamed `entryType` option to `type`
  86. - Renamed `entryType: 'both'` to `'files_directories'`
  87. - `EntryInfo`
  88. - Renamed `stat` to `stats`
  89. - Emitted only when `alwaysStat: true`
  90. - `dirent` is emitted instead of `stats` by default with `alwaysStat: false`
  91. - Renamed `name` to `basename`
  92. - Removed `parentDir` and `fullParentDir` properties
  93. - Supported node.js versions:
  94. - 3.x: node 8+
  95. - 2.x: node 0.6+
  96. ## License
  97. Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (<https://paulmillr.com>)
  98. MIT License, see [LICENSE](LICENSE) file.