UNPKG

fs-iterator

Version:

A file system iterator with filter and asyncIterator iterafaces. Supports Node 0.10 and above

49 lines (48 loc) 1.68 kB
import fs from 'fs'; import path from 'path'; import StackBaseIterator from 'stack-base-iterator'; import depthFirst from './depthFirst/index.js'; import fsCompat from './fs-compat/index.js'; const bigint = process.platform === 'win32' || /^(msys|cygwin)$/.test(process.env.OSTYPE); function defaultError(err) { return FSIterator.EXPECTED_ERRORS.indexOf(err.code) >= 0; // skip known issues } let FSIterator = class FSIterator extends StackBaseIterator { constructor(root, options = {}){ super(options), this.statOptions = { bigint }; this.options.error = options.error || defaultError; this.depth = options.depth === undefined ? Infinity : options.depth; this.readdirOptions = { encoding: 'utf8', withFileTypes: fs.Dirent && !options.alwaysStat }; this.root = path.resolve(root); let cancelled = false; function setup() { cancelled = true; } this.processing.push(setup); fsCompat.readdir(this.root, this.readdirOptions, (err, files)=>{ this.processing.remove(setup); if (this.done || cancelled) return; if (err) return this.end(err); if (files.length) { const stackItems = files.map((x)=>depthFirst.bind(null, { path: null, depth: 0, basename: x })).reverse(); this.push.apply(this, stackItems); } }); } }; FSIterator.EXPECTED_ERRORS = [ 'ENOENT', 'EPERM', 'EACCES', 'ELOOP' ]; export { FSIterator as default };