2.0.0 • Published 2 years ago

@pratiq/finder v2.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

Easily find and accumulate files by name, size, date and type.

Installation    Usage    Config    Dates    Extensions    API

Installation

Install with your preferred package manager

yarn add @pratiq/finder

Finder is provided as the default export

import finder from '@pratiq/finder'
const finder = require('@pratiq/finder')

Usage

Get all files in the current directory

import finder from '@pratiq/finder'

const data = finder()

Get all files at a specific path, and ignore type def files (.d.ts files)

import finder from '@pratiq/finder'

const data = finder({
    paths: ['../my/content'],
    ignoreTypes: ['d.ts'],
})

Get all markdown files from ./content that have been modified in the last hour

import finder from '@pratiq/finder'

const data = finder({
    paths: ['./content'],
    onlyTypes: ['md'],
    modifiedAfter: '-1h'
})

Simple Example

Get all files within the current directory, or at a specific path.

import finder from '@pratiq/finder'

const myFiles = finder('../my/content')

console.log( myFiles.files[0] )

Advanced Example

Provide advanced config for ignored paths/types and sorting

const fileData = finder({
    paths: ['../myFiles', './src'],         // search recursively in these two directories
    ignoreTypes: ['md', 'd.ts', 'test.js'], // ignore files with these three types
    modifiedAfter: '-15m',                  // only files modified within the last 15 minutes
    maxDepth: 10,                           // do not search deeper than 10 nested directories
    sortBy: 'size',                         // sort results by size (fileData.files)
    sortOrder: 'asc'                        // sort order of results (fileData.files)
})

Config Options

View the method definitions and examples below to get an idea of how to use the config parameters. Check the Type Definitions to look deeper into accepted values and types.

paths

An array of path strings pointing to directories to search within. Defaults to the current directory.
Default: ['.'] process.cwd()

finder({
    paths: [ './my/content', 'dist/bin' ],
})

ignorePaths

Array of paths to ignore.
Default: ['node_modules', '.git']

finder({
    ignorePaths: [ 'node_modules', '.git' ]
})

ignoreTypes

Array of file types to ignore. Overrides matching onlyTypes.
default: ['lock', '.gitignore']

finder({
    ignoreTypes: [ 'd.ts', 'config.json' ]
})

onlyTypes

Only return files that match the provided types. Will be overridden by matching ignoreTypes.
Default: []

finder({
    onlyTypes: [ 'md', 'json' ]
})

maxDepth

Maximum depth to recursively search directories during search. A value of 1 will only search a single level of nesting.
Default: 100

finder({
    maxDepth: 3
})

modifiedAfter

Only return files modified after the provided date.
default: null

finder({
    modifiedAfter:  '-10m'
})

modifiedBefore

Only return files modified before the provided date.
default: null

finder({
    modifiedBefore: '2008/1/1'
})

createdAfter

Only return files created after the provided date.
default: null

finder({
    createdAfter: 1682971265216
})

createdBefore

Only return files created before the provided date.
default: null

finder({
    createdBefore: -60_000
})

sortBy

The property used to sort the resulting files array, or maintain insertion order.
Default: null

finder({
    sortBy: 'name'
})

sortOrder

The order used to sort the resulting files array, or maintain insertion order.
Default: null

finder({
    sortOrder: 'desc'
})

replaceBase

A string used to replace the baseUrl or root dir of the paths searched. Helps in reducing dirMap complexity and stat.path length.
Default: null

finder({
    replaceBase: '@'
})

Date Formats

The properties that accept dates like createdBefore or modifiedAfter can accept any of the following types and values as valid dates. Any value that is not an instance of Date will be passed as the only argument to the date constructor.

⚠️ DATES ARE FORWARD INCLUSIVE

Standard Date Formats

TypeValueDescription
Datenew Date()The object returned from the Date constructor.
DateDate.now()A timestamp in unix format
number1682960778228A timestamp in unix format
string3/16/23A simple date string in any format accepted by the date constructor.

Relative Date Formats

TypeValueDescription
number-300Negative values are interpreted as a negative time offset in seconds (5 minutes)
string-5mTime strings that begin with - are interpreted as a negative offset in seconds and supports time units d days, h hours, m minutes, or the default of seconds.
// Find files modified within the last 5 days
finder({
    modifiedAfter: '-5d',
})

// Find files modified within the last day
// but not within the last ten minutes
finder({
    modifiedAfter: '-1d',
    modifiedBefore: '-10m'
})

File Types / Extensions

Files with no extension will be treated as txt plain text files. Dot files (.env, .gitignore) will be treated as . dot files. File types should not include leading periods unless referencing a 'dot' file like .gitignore.

The following values are all valid file types/extensions for finder:

d.ts    // types.d.ts
json    // package.json
lock    // yarn.lock
test.ts // unit.test.ts
ts      // test.ts

API

export type Finder = (config?: string | FinderConfig) => FinderReturn;

Config Properties

PropertyTypeDescription
pathsstring[]Array of paths to search within
ignorePathsstring[]Ignore file paths
ignoreTypesstring[]Ignore file types
onlyTypesstring[]Only return matching types
maxDepthnumberMaximum directory search depth
modifiedAfterDateOnly return files modified after provided date
modifiedBeforeDateOnly return files modified before provided date
createdAfterDateOnly return files created after provided date
createdBeforeDateOnly return files created before provided date
sortBySortMethodSort the results with the provided method
sortOrderSortOrderSort the results in ascending or descending order
replaceBasestringReplace the common baseUrl with a short string
const fileData = finder({
    paths: ['./my/content/'],
    onlyTypes: ['md', 'json'],
    modifiedAfter: '-20m',
    sortBy: 'date',
    sortOrder: 'desc',
    ...
})

Return Values

PropertyTypeDescription
lengthnumberNumber of files accumulated
filesFinderStat[]Array of resulting file data
newestFinderStatThe most recently modified or created file
oldestFinderStatThe least recently modified or created file
namesstring[]Array of file names with no leading path
typesstring[]Unique list of types found
baseDirstringBase directory path that was searched
dirMapObjectA map of the directory structure where values are file maps or path strings
const {
    files,
    newest,
    dirMap,
    baseDir,
    ...
} = finder()

Type Definitions

FinderConfig

export type Finder = (config?: string | FinderConfig) => FinderReturn;

export type FinderConfig = {
    // Array of path strings to search within 
    // default: `.` (current directory)
    // @example paths: ['myDir', '../../this-whole-dir'],
    paths: string[];

    // Array of paths to ignore 
    // default: `['node_modules', '.git']`
    // @example ignorePaths: ['../tests'],
    ignorePaths?: string[];
     
    // Array of file types to ignore.
    // default: `['lock']`
    // @example ignoreTypes: ['test.js'], */
    ignoreTypes?: string[];

    // Only return files that match the provided types.
    // default: `[]`
    // @example onlyTypes: ['md', 'txt'], */
    onlyTypes?: string[];

    // Maximum depth to search nested directories.  
    // default: `100`.
    // @example maxDepth: 8, */
    maxDepth?: number;

    // Only return files modified after the provided date.  
    // Accepts any valid date string or object (exclusive)
    // default: `null`
    // @example 
    // modifiedAfter: '01/24/1991'
    // modifiedAfter: 1641076200
    // modifiedAfter: '-20m'
    modifiedAfter?: Date;

    // Only return files modified before the provided date.  
    // Accepts any valid date string or object (exclusive)
    // default: `null`
    // @example 
    // modifiedAfter: '01/24/1991'
    // modifiedAfter: 1641076200
    // modifiedAfter: '-20m'
    modifiedBefore?: Date;
     
    // Only return files created after the provided date.  
    // Accepts any valid date string or object (exclusive)
    // default: `null`
    // @example 
    // modifiedAfter: '01/24/1991'
    // modifiedAfter: 1641076200
    // modifiedAfter: '-20m'
    createdAfter?: Date;
      
    // Only return files created before the provided date. 
    // Accepts any valid date string or object (exclusive)
    // default: `null`
    // @example 
    // modifiedAfter: '01/24/1991'
    // modifiedAfter: 1641076200
    // modifiedAfter: '-20m'
    createdBefore?: Date;
     
    // Sort the resulting file data by name, date, type, .etc 
    // default: `null`
    // @example 
    // sortBy: 'name', 
    // sortBy: 'size', 
     sortBy?: SortMethod;
     
    // Set the sort order used when sorting
    // @example 
    // sortOrder: 'desc',
    // sortOrder: 'asc',
    sortOrder?: SortOrder;
     
    // Replace the full file path with this string/path
    // default: `null`
    // @example replaceBase: '<base>/'
    // outputs: '<base>/path/to/file.txt'
    replaceBase?: string;
}

FinderReturn

export type FinderReturn =  {
    // Total number of files accumulated
    length: number;

    // Base directory of file search
    baseDir: null | string;

    // Array of file types accumulated
    types: string[];

    // Array of file names accumulated
    names: string[];

    // Array of resulting file data
    files: FinderStat[];

    // The most recently modified or created file
    newest: null | FinderStat;

    // The least recently modified or created file
    oldest: null | FinderStat;

    // A map of the directory structure where 
    // values are file maps or path strings
    dirMap: Object;
}

FinderStat

export type FinderStat = {
    // Full path to the file
    path: string;

    // File name - split at last '/' 
    name: string;

    // Inferred file type
    type: string;

    // File size (in bytes)
    size: number;
    
    // Last file modification date
    modified: Date;

    // File created date
    created: Date;
}

SortMethod

// Possible options for sort methods 
export type SortMethod = 'name' | 'size' | 'type' | 'created' | 'modified' | 'date'

SortOrder

// Possible options for sort orders 
export type SortOrder = 'asc' | 'desc'

Overview

Finder filters paths and types while recursively parsing directory contents and file stats to accumulate rich file data. If you need a fast and simple file matcher for file paths only, try globby.

License

MIT This project is licensed under the terms of the MIT license. See the LICENSE file for the full text.

2.0.0

2 years ago

1.0.23

2 years ago

1.0.22

2 years ago

1.0.21

2 years ago

1.0.20

2 years ago

1.0.19

2 years ago

1.0.18

2 years ago

1.0.17

2 years ago

1.0.16

2 years ago

1.0.15

2 years ago

1.0.14

2 years ago

1.0.13

2 years ago

1.0.12

2 years ago

1.0.11

2 years ago

1.0.10

2 years ago

1.0.9

2 years ago

1.0.8

2 years ago

1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago