• Stars
    star
    382
  • Rank 112,241 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 12 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Recursive version of fs.readdir with streaming api.

readdirp Weekly downloads

Recursive version of fs.readdir. Exposes a stream API and a promise API.

npm install readdirp
const readdirp = require('readdirp');

// Use streams to achieve small RAM & CPU footprint.
// 1) Streams example with for-await.
for await (const entry of readdirp('.')) {
  const {path} = entry;
  console.log(`${JSON.stringify({path})}`);
}

// 2) Streams example, non for-await.
// Print out all JS files along with their size within the current folder & subfolders.
readdirp('.', {fileFilter: '*.js', alwaysStat: true})
  .on('data', (entry) => {
    const {path, stats: {size}} = entry;
    console.log(`${JSON.stringify({path, size})}`);
  })
  // Optionally call stream.destroy() in `warn()` in order to abort and cause 'close' to be emitted
  .on('warn', error => console.error('non-fatal error', error))
  .on('error', error => console.error('fatal error', error))
  .on('end', () => console.log('done'));

// 3) Promise example. More RAM and CPU than streams / for-await.
const files = await readdirp.promise('.');
console.log(files.map(file => file.path));

// Other options.
readdirp('test', {
  fileFilter: '*.js',
  directoryFilter: ['!.git', '!*modules'],
  // directoryFilter: (di) => di.basename.length === 9
  type: 'files_directories',
  depth: 1
});

For more examples, check out examples directory.

API

const stream = readdirp(root[, options]) — Stream API

  • Reads given root recursively and returns a stream of entry infos
  • Optionally can be used like for await (const entry of stream) with node.js 10+ (asyncIterator).
  • on('data', (entry) => {}) entry info for every file / dir.
  • on('warn', (error) => {}) non-fatal Error that prevents a file / dir from being processed. Example: inaccessible to the user.
  • on('error', (error) => {}) fatal Error which also ends the stream. Example: illegal options where passed.
  • on('end') — we are done. Called when all entries were found and no more will be emitted.
  • on('close') — stream is destroyed via stream.destroy(). Could be useful if you want to manually abort even on a non fatal error. At that point the stream is no longer readable and no more entries, warning or errors are emitted
  • To learn more about streams, consult the very detailed nodejs streams documentation or the stream-handbook

const entries = await readdirp.promise(root[, options]) — Promise API. Returns a list of entry infos.

First argument is awalys root, path in which to start reading and recursing into subdirectories.

options

  • fileFilter: ["*.js"]: filter to include or exclude files. A Function, Glob string or Array of glob strings.
    • Function: a function that takes an entry info as a parameter and returns true to include or false to exclude the entry
    • Glob string: a string (e.g., *.js) which is matched using picomatch, so go there for more 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.
    • Array of glob strings: either need to be all inclusive or all exclusive (negated) patterns otherwise an error is thrown. ['*.json', '*.js'] includes all JavaScript and Json files. ['!.git', '!node_modules'] includes all directories except the '.git' and 'node_modules'.
    • Directories that do not pass a filter will not be recursed into.
  • directoryFilter: ['!.git']: filter to include/exclude directories found and to recurse into. Directories that do not pass a filter will not be recursed into.
  • depth: 5: depth at which to stop recursing even if more subdirectories are found
  • 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.
  • 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.
  • lstat: false: include symlink entries in the stream along with files. When true, fs.lstat would be used instead of fs.stat

EntryInfo

Has the following properties:

  • path: 'assets/javascripts/react.js': path to the file/directory (relative to given root)
  • fullPath: '/Users/dev/projects/app/assets/javascripts/react.js': full path to the file/directory found
  • basename: 'react.js': name of the file/directory
  • dirent: fs.Dirent: built-in dir entry object - only with alwaysStat: false
  • stats: fs.Stats: built in stat object - only with alwaysStat: true

Changelog

  • 3.5 (Oct 13, 2020) disallows recursive directory-based symlinks. Before, it could have entered infinite loop.
  • 3.4 (Mar 19, 2020) adds support for directory-based symlinks.
  • 3.3 (Dec 6, 2019) stabilizes RAM consumption and enables perf management with highWaterMark option. Fixes race conditions related to for-await looping.
  • 3.2 (Oct 14, 2019) improves performance by 250% and makes streams implementation more idiomatic.
  • 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".
  • 3.0 brings huge performance improvements and stream backpressure support.
  • Upgrading 2.x to 3.x:
    • Signature changed from readdirp(options) to readdirp(root, options)
    • Replaced callback API with promise API.
    • Renamed entryType option to type
    • Renamed entryType: 'both' to 'files_directories'
    • EntryInfo
      • Renamed stat to stats
        • Emitted only when alwaysStat: true
        • dirent is emitted instead of stats by default with alwaysStat: false
      • Renamed name to basename
      • Removed parentDir and fullParentDir properties
  • Supported node.js versions:
    • 3.x: node 8+
    • 2.x: node 0.6+

License

Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (https://paulmillr.com)

MIT License, see LICENSE file.

More Repositories

1

chokidar

Minimal and efficient cross-platform file watching library
JavaScript
10,957
star
2

encrypted-dns

DNS over HTTPS config profiles for iOS & macOS
3,316
star
3

es6-shim

ECMAScript 6 compatibility shims for legacy JS engines
JavaScript
3,114
star
4

dotfiles

Colourful & robust configuration files and utilities for Mac, Linux & BSD
Shell
1,199
star
5

exoskeleton

Faster and leaner Backbone for your HTML5 apps
JavaScript
880
star
6

noble-secp256k1

Fastest 4KB JS implementation of secp256k1 signatures and ECDH
JavaScript
757
star
7

noble-curves

Audited & minimal JS implementation of elliptic curve cryptography.
JavaScript
675
star
8

noble-hashes

Audited & minimal JS implementation of hash functions, MACs and KDFs.
JavaScript
573
star
9

console-polyfill

Browser console methods polyfill.
JavaScript
436
star
10

noble-ed25519

Fastest 4KB JS implementation of ed25519 signatures
JavaScript
419
star
11

top-github-users

GitHub top-1000 generation script
CoffeeScript
259
star
12

ostio

Your open-source talks place.
JavaScript
247
star
13

noble-bls12-381

DEPRECATED: use noble-curves instead. Fastest JS implementation of BLS12-381.
TypeScript
202
star
14

noble-ciphers

Auditable & minimal JS implementation of Salsa20, ChaCha and AES
TypeScript
188
star
15

micro-eth-signer

Minimal library for Ethereum transactions, addresses and smart contracts.
JavaScript
187
star
16

code-style-guides

Idiomatic, widely-used code style guides for various programming languages.
164
star
17

scure-btc-signer

Audited & minimal library for creating, signing & decoding Bitcoin transactions.
JavaScript
151
star
18

qr

Minimal node.js & browser QR Code Pattern reader and generator
JavaScript
137
star
19

scaffolt

Dead-simple JSON-based scaffolder.
JavaScript
125
star
20

scure-bip39

Secure, audited & minimal implementation of BIP39 mnemonic phrases
TypeScript
119
star
21

scure-base

Secure, audited & 0-deps implementation of bech32, base64, base32, base16 & base58
JavaScript
114
star
22

async-each

No-bullshit, ultra-simple, 40-lines-of-code async parallel forEach / map function for JavaScript.
JavaScript
105
star
23

noble-post-quantum

Auditable & minimal JS implementation of public-key post-quantum cryptography
TypeScript
82
star
24

scure-starknet

Audited & minimal JS implementation of Starknet cryptography.
JavaScript
69
star
25

ostio-api

Your open-source talks place. Rails backend.
Ruby
69
star
26

tx-tor-broadcaster

CLI utility that broadcasts BTC, ETH, SOL, ZEC & XMR transactions through TOR using public block explorers
JavaScript
68
star
27

micro-sol-signer

Create, sign & decode Solana transactions with minimum deps
JavaScript
61
star
28

scure-bip32

Secure, audited & minimal implementation of BIP32 hierarchical deterministic (HD) wallets.
TypeScript
61
star
29

micro-web3

Typesafe Web3 with minimum deps: call eth contracts directly from JS. Batteries included
TypeScript
59
star
30

native-notifier

Use native system notifications in node.js without third-party libraries
JavaScript
56
star
31

chieftain

New generation imageboard. Built with Python / Django.
Python
49
star
32

micro-ordinals

Minimal JS library for ordinals and inscriptions on top of scure-btc-signer
JavaScript
43
star
33

micro-key-producer

Produces secure keys and passwords. Supports SSH, PGP, BLS, OTP and many other formats
TypeScript
43
star
34

loggy

Colorful stdstream dead-simple logger for node.js.
JavaScript
42
star
35

micro-ftch

Wrappers for built-in fetch() enabling killswitch, logging, concurrency limit and other features.
JavaScript
40
star
36

Array.prototype.find

Simple ES6 Array.prototype.find polyfill for older environments.
JavaScript
38
star
37

micro-packed

Define complex binary structures using composable primitives
TypeScript
38
star
38

micro-otp

One Time Password generation via RFC 6238
JavaScript
35
star
39

micro-bmark

Benchmark your node.js projects with nanosecond resolution.
JavaScript
34
star
40

pushserve

Dead-simple pushState-enabled command-line http server.
JavaScript
32
star
41

LiveScript.tmbundle

A TextMate, Chocolat and Sublime Text bundle for LiveScript
Python
31
star
42

jage

age-encryption.org tool implementation in JavaScript
TypeScript
29
star
43

read-components

Read bower and component(1) components
JavaScript
28
star
44

Array.prototype.findIndex

Simple ES6 Array.prototype.findIndex polyfill for older environments.
JavaScript
28
star
45

mnp

My new passport
JavaScript
28
star
46

nip44

NIP44 spec and implementations of encrypted messages for nostr
C
26
star
47

github-pull-req-stats

Stats from GitHub repos about accepted / closed pull requests.
JavaScript
25
star
48

micro-aes-gcm

0-dep wrapper around webcrypto AES-GCM. Has optional RFC 8452 SIV implementation.
JavaScript
25
star
49

steg

Simple and secure steganography
TypeScript
23
star
50

micro-password-generator

Utilities for password generation and estimation with support for iOS keychain
TypeScript
18
star
51

tag-shell

Use ES6 template tags for your node.js shell commands.
JavaScript
17
star
52

papers

Papers i've read and / or wanted to save
17
star
53

micro-should

Simplest zero-dependency testing framework, a drop-in replacement for Mocha.
JavaScript
17
star
54

noble-ripemd160

Noble RIPEMD160. High-security, easily auditable, 0-dep, 1-file hash function
TypeScript
17
star
55

bls12-381-keygen

BLS12-381 Key Generation compatible with EIP-2333.
TypeScript
16
star
56

micro-promisify

Convert callback-based JS function into promise. Simple, 10LOC, no deps.
JavaScript
16
star
57

micro-base58

Fast and beautiful base58 encoder without dependencies.
TypeScript
15
star
58

micro-rsa-dsa-dh

Minimal JS implementation of older cryptography algorithms: RSA, DSA, DH.
TypeScript
15
star
59

lastfm-tools

Last.FM data reclaimer (backuper, helper and analyzer).
Ruby
14
star
60

fetch-streaming

Simple XMLHTTPRequest-based `fetch` implementation for streaming content.
JavaScript
14
star
61

micro-ed25519-hdkey

Minimal implementation of SLIP-0010 hierarchical deterministic (HD) wallets
JavaScript
14
star
62

unicode-categories

ECMAscript unicode categories. Useful for lexing.
12
star
63

noble.py

Noble cryptographic libraries in Python. High-security, easily auditable, 0-dep pubkey, scalarmult & EDDSA.
Python
11
star
64

argumentum

No-bullshit option parser for node.js.
JavaScript
8
star
65

trusted-setups

Easily access trusted setups in JS. Includes KZG / ETH
JavaScript
7
star
66

micro-es7-shim

No-bullshit super-simple es7 collections shim for Array#includes, Object.values, Object.entries
JavaScript
7
star
67

jsbt

Build tools for js projects. Includes tsconfigs, templates and CI workflows
JavaScript
7
star
68

eth-vectors

Comprehensive official vectors for ETH
JavaScript
7
star
69

micro-ff1

Format-preserving encryption algorithm (FPE-FF1) specified in NIST Special Publication 800-38G.
TypeScript
6
star
70

backup

Backup of all my projects in a single signed file
JavaScript
6
star
71

quickly-copy-file

Quickly copy file from one path to another. No bullshit, ultra-simple, async and just one dep.
JavaScript
6
star
72

microtemplates

John Resig's micro-templates aka underscore templates. No-bullshit and small
JavaScript
6
star
73

popular-user-agents

Regularly updated list of popular user agents aka browser versions
JavaScript
6
star
74

paulmillr.github.io

JavaScript
5
star
75

roy.tmbundle

Roy TextMate, Chocolat & Sublime Text 2 bundle
5
star
76

qr-code-vectors

QR Code test vectors
Python
4
star
77

paulmillr

4
star
78

aesscr

Use AES-256-GCM + Scrypt to encrypt files.
JavaScript
3
star
79

universal-path

Cross-platform universal node.js `path` module replacement that works better with Windows
JavaScript
2
star
80

fcache

fs.readFile cache for node.js build systems & watchers
JavaScript
2
star
81

rn-bigint

Java
1
star
82

packed

https://github.com/paulmillr/micro-packed
1
star
83

unused-test-repo

JavaScript
1
star