find-import
v1.0.11
Published
Find and load first instance of js/json in parent directories.
Downloads
581
Readme
find-import
Find and load first instance of js/json in parent directories.
Contents
Introduction
Load the first instance of a found module.
Optionally specify depth preference to prefer "top-most" packages.
Supports .json
, .cjs
, .mjs
, and .js
.
Returns the path and contents of the found module.
Install
npm i find-import
Example
Given file structure
/
└─┬ root
├── my-file.cjs // module.exports = { abc: 123 }
└─┬ my-package
└── my-file.json // { "foo": "bar" }
// cwd = /root/my-package
import { findImport } from 'find-import';
let found;
found = await findImport(['my-file.cjs', 'my-file.json']);
found.content // { foo: 'bar' }
found.filePath // /root/my-package/my-file.json
found = await findImport(['my-file.cjs', 'my-file.json'], {
direction: 'down',
});
found.content // { abc: 123 }
found.filePath // /root/my-file.cjs
found = await findImport(['my-file.cjs', 'my-file.json'], {
direction: 'down',
startAt: '/root/my-package',
});
found.filePath // /root/my-package/my-file.json
found = await findImport(['my-file.cjs', 'my-file.json'], {
cwd: '/root',
});
found.filePath // /root/my-package/my-file.cjs
Usage
find-import
is an ESM module. That means it must be import
ed. To load from a CJS module, use dynamic import const { findImport } = await import('find-import');
.
API
findImport(fileNames, options?)
Finds first instance of matching module, and loads. Returns file path to module and content.
Note that content
is the result of a dynamic import()
call. If accessing the default content, it may be necessary/convenient to extract that content. See default-import for a potential solution.
fileNames
string or array of strings
List of file names to search for in each directory.
options
cwd
- Type:
string
orURL
- optional, defaults to
process.cwd()
- Directory to use as base directory.
- See
parse-cwd
.
- Type:
direction
'up'
(default) or'down'
- direction to search for files.
'up'
indicates/foo/bar
->/foo
->/
'down'
is opposite,/
->/foo
->/foo/bar
startAt
- Type:
string
orURL
- optional, defaults to
/
- Top-most "root" directory to limit search.
- Type: