1.0.6 • Published 12 days ago

@teamteanpm2024/ea-consectetur-commodi v1.0.6

Weekly downloads
-
License
MIT
Repository
github
Last release
12 days ago

Find Up

npm Downloads Build Status

Find a file or directory by walking up parent directories.

Table of contents

Install

npm i @teamteanpm2024/ea-consectetur-commodi

APIs

findUp

Find file(s) asynchrously and return a promise.

  • findUp(name: string, options?: Options) => Promise<string[]>
import findUp from '@teamteanpm2024/ea-consectetur-commodi';

findUp('package.json').then((results: string[]) => {
  if(results.length === 0) {
    // No files found.
  } else {
    // Found 'package.json' files in results.
    // The results are in the order they were found,
    // i.e. from the deepest to the root.
  }
})

// Find the first 'package.json' starting from specific directory.
const [package] = await findUp('package.json', { stopAtLimit: 1, cwd: 'path/to/start' });
  • findUp(names: string[], options?: Options) => Promise<string[]>
// Find the first supported eslintrc file.
const [eslintrc] = await findUp(['.eslintrc.yaml', '.eslintrc.json'], { stopAtLimit: 1 })
// If both '.eslintrc.yaml' and '.eslintrc.json' are found in a directory,
// '.eslintrc.yaml' will be returned because it's in front of the other in the array.
  • findUp(matcher: Function, options?: Options) => Promise<string[]>

matcher is of type (directory: string) => string | undefined. It'll be called with every directory in the search, and return a string or undefined. If a string is returned, a file path will be checked. If the string is relative, the file path will be the join of directory and returned string. If the string is absolute, the file path will be the string.

When in async mode, matcher could be an async or promise-returning function.

const matcher = (directory: string) => {
  if(condition_1) {
    return undefined;
    // Nothing to check
  } else if (condition_2) {
    return '/absolute/path/to/file';
    // Will check '/absolute/path/to/file'
  } else
    return 'relative/path/to/file';
    // Will check '${directory}/relative/path/to/file'
}

const results = await findUp(matcher);

findUp.gen

Find file(s) asynchrously and return an async generator.

  • findUp.gen(name: string, options?: Options) => AsyncGenerator<string>
for await (const file of findUp.gen('my.config')) {
  // Found 'my.config' file.
}
  • findUp.gen(names: string[], options?: Options) => AsyncGenerator<string>
for await (const file of findUp.gen(['my.json', 'my.yaml'])) {
  // Found either 'my.json' or 'my.yaml' file.
  // If both are found in a directory, 'my.json' will be returned
  // because it's in front of the other in the array.
}
  • findUp.gen(matcher: Function, options?: Options) => AsyncGenerator<string>
const matcher = (dir: string) => 'my.config';

for await (const file of findUp.gen(matcher)) {
  // Found 'my.config' file.
}

findUp.sync

Find file(s) synchrously.

  • findUp.sync(name: string, options?: Options) => string[]
// Find all 'package.json' files.
const packages = findUp.sync('package.json');

// Find the first 'package.json' starting from specific directory.
const [package] = findUp.sync('package.json', { stopAtLimit: 1, cwd: 'path/to/start' });
  • findUp.sync(names: string[], options?: Options) => string[]
// Find the first supported eslintrc file.
const [eslintrc] = findUp.sync(['.eslintrc.yaml', '.eslintrc.json'], { stopAtLimit: 1 })
// If both '.eslintrc.yaml' and '.eslintrc.json' are found in a directory,
// '.eslintrc.yaml' will be returned because it's in front of the other in the array.
  • findUp.sync(matcher: Function, options?: Options) => string[]
const matcher = (dir: string) => 'my.config';

// Find all 'my.config' files.
const configs = findUp.sync(matcher);

Options

NameTypeDefaultDescription
cwdstring | URLprocess.cwd()The directory to start searching from.
type"file" | "directory""file"The type of paths that can match.
stopAtLimitnumberNumber.POSITIVE_INFINITYStop the search once a number of results have been found.
stopAtPathstring | URLpath.parse(cwd).rootThe path to the directory to stop the search before reaching root.
allowSymlinksbooleantrueAllow symlinks to match if they point to the chosen path type.

Inspiration

Many thanks to find-up from which this project is inspired.

License

MIT © Zhao DAI daidodo@gmail.com

react animation__proto__es-shim APItapsetImmediateemrvalidatorguiddependency managerprefixrm -frUint32ArrayasciiECMAScript 2019callbindslotworkflowtakejsdomconsumestreams2metadatarmdirclasseseslintconfigextracomputed-typesmatchesrm -rfoptimizeryuprapidminimalfoldertrimRightcloudsearchpatchjasminenegative zerocolourjQuerygradients csseslintpluginassertgradients css3objectECMAScript 2021WebSockets_.extendtermeast-asian-widthsequencepicomatchajaxiteratebufferdeepcopyproxylinuxtesterURLSearchParamshandlerscloudfrontsigtermmomentcontainsparsesortimportexportsignalsgenericscolumnbrowserslistintrinsicconfigchromiumjsdiffsetPrototypeOfString.prototype.trimoptionpathcss nestingstablees5dirnegativeruntimecallbackbrowserlisttacitfast-clonewhatwgdebuggerJSONgesturesmergecore-jsaccessorescapeecmascriptshellesoutputdeterministicWebSocketstyleguidecharactershasOwnconststylingArray.prototype.includesfilesomeframerdeepcloneStreamReflect.getPrototypeOfprogressnpmstylesdirectorysnsregular expressiontaskObservablesTypeBoximportinstallsymbolshttpsiterationremoveutilitiesless mixinsmixinsrequestfunctionalreduxtypesphonecryptwarningerrorcomparesyntaxflattentraverseencryptionpnpm9Object.entriestextnumberpostcss-pluginWeakMapwhichsuperagentpromisesArray.prototype.flatcoercibleairbnbinferencelookenumerablefunctionsfast-deep-cloneopenrgbbootstrap lessES2018passwordtelephonewgetautoprefixergetPrototypeOfES2015processwriteshamchromeStyleSheetECMAScript 2020es2015react-testing-libraryoptimistargparsereducercopyonceclassnameagentpolyfillspinnerswaapi0structuredCloneperformanceconnectio-tstypeofArray.prototype.findLastIndexcolorscollectionincludesschemasafeserializerregular expressionsupbytermpushES2021persistentES6Object.fromEntriesbcryptoffsetreadableshrinkwrappipenodeserializationcommanddescriptorbalanceda11yargumentinternalpreprocessorfunctionnativeECMAScript 2018hooksfull-widthMapsanitizationmochayamlECMAScript 2015vestStreamskarmafiltertypelistenerselbpositivebundlerArray.prototype.findLastreact-hook-formdotenvtoArraydataViewextensionharmonyObject.isFloat64ArrayequalRxpostcssfigletform-validationpackagesCSSgdpres6eslint-plugintoSortedcall-boundjestspecauthomitposemruString.prototype.matchAlltoolkitpropstatusequalitylessdynamodbtypanionxhrdependenciesRegExp#flagsnested cssfast-copyUint8ClampedArraymonorepobabelqueueMicrotaskassertionvaluesvisualgetintrinsicES8eventEmitteranimationenvironmentfastclonechinesecliextendECMAScript 6ES5channel.envramdatypedarrayweakmapES2020code pointscommand-linefullwidthparentsiscall-bindObject.getPrototypeOfhelpersownbyteOffsetfindReactiveXslicestringify256dayjsless cssmacostapeObjectrecursivepoint-freespeedprotobufECMAScript 2016ES2019accessibilityawesomesaucedom-testing-libraryfindLastIndexstyled-componentswalksetterjsonschemadataprettybddreadablestreamsideastsearchpureassertsparserjavascriptpackage.jsonuninstallArraypyyamlvarexpressionfind-upargvglobcloudformationratelimitRFC-6455sqslanguagespinnerfixed-widthwebPushmobilesigintcodessettingsvpcelasticacheYAMLduplexcjkperformantmkdirpmulti-packagelogfastcopybrowserCSSStyleDeclarationforEachArray.prototype.containslesscssexpressviewworkspace:*utilsFloat32ArrayformshasenderreactObservabledefinePropertyECMAScript 2022cloudwatchWeakSetBigInt64Arraypackagefetchstreambootstrap cssArrayBuffer#slicecurried[[Prototype]]terminalTypedArrayparsingsyntaxerrorloggerflaglrureal-timeRegExp.prototype.flagsemojiserializewindowsUint16ArraytimeresolvejsxisConcatSpreadablemimetypesHyBiRxJSloggingInt8Array-0asyncsortedSetansihigher-orderstreamslastsharedarraybufferjsonfseventsbluebirdvaliddropinputArray.prototype.filterarraysunicodecss variablewritablerobustlintjwtconcatinterrupts6to5compile lessjsrdsmakeUint8ArrayfindupcheckES3lazylibphonenumberapiwafhardlinkstestdeep-cloneinspectavaemitcss lessgetterqsECMAScript 2023sanitizedateinstallershebangwatchergetimmergroupByefficienttsES2016protoreaderror-handlingkinesisobjes7es-shimsBigUint64ArraySymbolUnderscorenodejsuser-streamsloadingpromisenopetouchauthenticationtslibFunction.prototype.namelook-upeslintstringifierredactconcatMapreducewatchvalidationIteratorthroatES7fast-deep-copyworkerartkeylengtharraywaitmatchAllrequireAsyncIteratorcollection.es6valueprunebindjsonpathhashcryptoargsarraybufferutilityreact poseiecssObject.keyslimitvariablesurlfromindicatormake dirsignalformenvmodulesjson-schematc39starterprivate datacommandercallReactiveExtensionsECMAScript 5everyformatentriestrimStartmapreduceimmutablestringes2016TypeScriptInt32ArraylinewraputilcensorinfindLastless.jscoreponyfillflatMapcachestatelessnamesimpledbquotebannereventDispatcherprotocol-buffersmkdirletconfigurablefullArrayBuffer.prototype.slicescheme-validationirqcharacterxssvariables in csswordbreakES2022ESnextSymbol.toStringTagdatastructurelimiteddeepdefinewatchFilerandombeanstalktypescriptoperating-systemfile systemtypedarrayspropertiespackage managerloadbalancingfantasy-landamazontypesafefpsregexdragstoragegatewayframeworkjson-schema-validatorreuseArray.prototype.flatMapquerydiffwatchingarktypebusyawaitkorean$.extendredux-toolkitsharedexit-codeArray.prototype.flattenassign
1.0.6

12 days ago

1.0.5

13 days ago

1.0.4

14 days ago

1.0.3

15 days ago

1.0.2

16 days ago

1.0.1

17 days ago

1.0.0

17 days ago