What is locate-path?
The locate-path npm package is designed to find a file or directory by looking for it in multiple paths. It is useful for situations where you need to locate a file but are unsure of its exact location within a list of possible directories. It can be used synchronously or asynchronously and supports both promises and async/await syntax.
What are locate-path's main functionalities?
Asynchronous Path Location
This feature allows you to asynchronously locate a file or directory from an array of paths. The first path that contains the file or directory is returned.
const locatePath = require('locate-path');
(async () => {
const foundPath = await locatePath(['unicorn.png', 'rainbow.png'], {cwd: 'images'});
console.log(foundPath);
//=> 'images/unicorn.png'
})();
Synchronous Path Location
This feature provides a synchronous way to locate a file or directory from an array of paths. It is useful when you need to find a path in a blocking manner.
const locatePath = require('locate-path');
const foundPath = locatePath.sync(['unicorn.png', 'rainbow.png'], {cwd: 'images'});
console.log(foundPath);
//=> 'images/unicorn.png'
Other packages similar to locate-path
find-up
The find-up package is similar to locate-path in that it helps you find a file or directory by searching upwards from a given directory. It differs in that it searches up the directory tree, starting from the current directory, rather than across a list of specified paths.
globby
Globby is a package that allows you to find files using glob patterns. While locate-path is used to find a file from a list of paths, globby can search for files matching patterns, which can be more flexible in certain scenarios.
resolve-from
Resolve-from is a package that resolves the path of a module from a given path, similar to require.resolve but from a specified directory. It is more specific to module resolution compared to locate-path which is for general file or directory location.
locate-path
Get the first path that exists on disk of multiple paths
Install
$ npm install --save locate-path
Usage
Here we find the first file that exists on disk, in array order.
const locatePath = require('locate-path');
const files = [
'unicorn.png',
'rainbow.png',
'pony.png'
];
locatePath(files, {concurrency: 1}).then(foundPath => {
console.log(foundPath);
});
API
locatePath(input, [options])
Returns a Promise
for the first path that exists or undefined
if none exists.
input
Type: Iterable<string>
Paths to check.
Set {concurrency: 1}
to preserve the search order.
options
Type: Object
concurrency
Type: number
Default: Infinity
Minimum: 1
Number of concurrently pending promises.
locatePath.sync(input)
Returns the first path that exists or undefined
if none exists.
input
Type: Iterable<string>
Paths to check.
Related
License
MIT © Sindre Sorhus