Cosmiconfig
Find and load configuration from a package.json property, rc file, TypeScript module, and more!
Install / Use
/learn @cosmiconfig/CosmiconfigREADME
cosmiconfig
Cosmiconfig searches for and loads configuration for your program.
It features smart defaults based on conventional expectations in the JavaScript ecosystem. But it's also flexible enough to search wherever you'd like to search, and load whatever you'd like to load.
By default, Cosmiconfig will check the current directory for the following:
- a
package.jsonproperty - a JSON or YAML, extensionless "rc file"
- an "rc file" with the extensions
.json,.yaml,.yml,.js,.ts,.mjs, or.cjs - any of the above two inside a
.configsubdirectory - a
.config.js,.config.ts,.config.mjs, or.config.cjsfile
For example, if your module's name is "myapp", cosmiconfig will search up the directory tree for configuration in the following places:
- a
myappproperty inpackage.json - a
.myapprcfile in JSON or YAML format - a
.myapprc.json,.myapprc.yaml,.myapprc.yml,.myapprc.js,.myapprc.ts,.myapprc.mjs, or.myapprc.cjsfile - a
myapprc,myapprc.json,myapprc.yaml,myapprc.yml,myapprc.js,myapprc.ts,myapprc.mjs, ormyapprc.cjsfile inside a.configsubdirectory - a
myapp.config.js,myapp.config.ts,myapp.config.mjs, ormyapp.config.cjsfile
Optionally, you can tell it to search up the directory tree using [search strategies], checking each of these places in each directory, until it finds some acceptable configuration (or hits the home directory).
Table of contents
- Installation
- Usage for tooling developers
- Result
- Asynchronous API
- Synchronous API
- cosmiconfigOptions
- Loading JS modules
- Caching
- Differences from rc
- Usage for end users
- Contributing & Development
Installation
npm install cosmiconfig
Tested in Node 14+.
Usage for tooling developers
If you are an end user (i.e. a user of a tool that uses cosmiconfig, like prettier or stylelint),
you can skip down to the end user section.
Create a Cosmiconfig explorer, then either search for or directly load a configuration file.
const { cosmiconfig, cosmiconfigSync } = require('cosmiconfig');
// ...
const explorer = cosmiconfig(moduleName);
// Search for a configuration by walking up directories.
// See documentation for search, below.
explorer.search()
.then((result) => {
// result.config is the parsed configuration object.
// result.filepath is the path to the config file that was found.
// result.isEmpty is true if there was nothing to parse in the config file.
})
.catch((error) => {
// Do something constructive.
});
// Load a configuration directly when you know where it should be.
// The result object is the same as for search.
// See documentation for load, below.
explorer.load(pathToConfig).then(/* ... */);
// You can also search and load synchronously.
const explorerSync = cosmiconfigSync(moduleName);
const searchedFor = explorerSync.search();
const loaded = explorerSync.load(pathToConfig);
Result
The result object you get from search or load has the following properties:
- config: The parsed configuration object.
undefinedif the file is empty. - filepath: The path to the configuration file that was found.
- isEmpty:
trueif the configuration file is empty. This property will not be present if the configuration file is not empty.
Asynchronous API
cosmiconfig()
const { cosmiconfig } = require('cosmiconfig');
const explorer = cosmiconfig(moduleName, /* optional */ cosmiconfigOptions)
Creates a cosmiconfig instance ("explorer") configured according to the arguments, and initializes its caches.
moduleName
Type: string. Required.
Your module name. This is used to create the default [searchPlaces] and [packageProp].
If your [searchPlaces] value will include files, as it does by default (e.g. ${moduleName}rc), your moduleName must consist of characters allowed in filenames. That means you should not copy scoped package names, such as @my-org/my-package, directly into moduleName.
[cosmiconfigOptions] are documented below.
You may not need them, and should first read about the functions you'll use.
explorer.search()
explorer.search([searchFrom]).then(result => { /* ... */ })
Searches for a configuration file. Returns a Promise that resolves with a [result] or with null, if no configuration file is found.
You can do the same thing synchronously with [explorerSync.search()].
Let's say your module name is goldengrahams so you initialized with const explorer = cosmiconfig('goldengrahams');.
Here's how your default [search()] will work:
- Starting from
process.cwd()(or some other directory defined by thesearchFromargument to [search()]), look for configuration objects in the following places:- A
goldengrahamsproperty in apackage.jsonfile. - A
.goldengrahamsrcfile with JSON or YAML syntax. - A
.goldengrahamsrc.json,.goldengrahamsrc.yaml,.goldengrahamsrc.yml,.goldengrahamsrc.js,.goldengrahamsrc.ts,.goldengrahamsrc.mjs, or.goldengrahamsrc.cjsfile. (To learn more about how JS files are loaded, see ["Loading JS modules"].) - A
goldengrahamsrc,goldengrahamsrc.json,goldengrahamsrc.yaml,goldengrahamsrc.yml,goldengrahamsrc.js,goldengrahamsrc.ts,goldengrahamsrc.mjs, orgoldengrahamsrc.cjsfile in the.configsubdirectory. - A
goldengrahams.config.js,goldengrahams.config.ts,goldengrahams.config.mjs, orgoldengrahams.config.cjsfile. (To learn more about how JS files are loaded, see ["Loading JS modules"].)
- A
- If none of those searches reveal a configuration object, continue depending on the current search strategy:
- If it's
none(which is the default if you don't specify a [stopDir] option), stop here and return/resolve withnull. - If it's
global(which is the default if you specify a [stopDir] option), move up one directory level and try again, recursing until arriving at the configured [stopDir] option, which defaults to the user's home directory.- After arriving at the [
stopDir], the global configuration directory (as defined by [env-paths] without prefix) is also checked, looking at the filesconfig,config.json,config.yaml,config.yml,config.js,config.ts,config.cjs, andconfig.mjsin the directory~/.config/goldengrahams/(on Linux; see [env-paths] documentation for other OSs).
- After arriving at the [
- If it's
project, check whether apackage.jsonfile is present in the current directory, and if not, move up one directory level and try again, recursing until there is one.
- If it's
- If at any point a parsable configuration is found, the [
search()] Promise resolves with its [result] (or, with [explorerSync.search()], the [result] is returned). - If no configuration object is found, the [
search()] Promise resolves withnull(or, with [explorerSync.search()],nullis returned). - If a configuration object is found but is malformed (causing a parsing error), the [
search()] Promise rejects with that error (so you should.catch()it). (Or, with [explorerSync.search()], the error is thrown.)
If you know exactly where your configuration file should be, you can use [load()], instead.
The search process is highly customizable.
Use the cosmiconfig options [searchPlaces] and [loaders] to precisely define where you want to look for configurations and how you want to load them.
searchFrom
Type: string.
Default: process.cwd().
A filename.
[search()] will start its search here.
If the value is a directory, that's where the search starts. If it's a file, the search starts in that file's directory.
explorer.load()
explorer.load(loadPath).then(result => { /* ... */ })
Loads a configuration file. Returns a Promise that resolves with a [result] or rejects with an error (if the file does not exist or cannot be loaded).
Use load if you already know where the configuration file is and you just need to load it.
explorer.load('load/this/file.json'); // Tries to load load/this/file.json.
If you load a package.json file, the result will be derived from whatever property is specified as your [packageProp].
package.yaml will work as well if you specify these file names in your [searchPlaces].
You can do the same thing synchronously with [explorerSync.load()].
explorer.clearLoadCache()
Clears the cache used in [load()].
explorer.clearSearchCache()
Clears the cache used in [search()].
explorer.clearCaches()
Performs both [clearLoadCache()] and [clearSearchCache()].
Synchronous API
cosmiconfigSync()
`
Related Skills
node-connect
340.5kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
84.2kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
340.5kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
84.2kCommit, push, and open a PR