Cosmiconfig searches for and loads configuration for your program.
By default, Cosmiconfig will start where you tell it to start and search up the directory tree for the following:
- a JSON or YAML, extensionless "rc file"
- an "rc file" with the extensions
For example, if your module's name is "soursocks", cosmiconfig will search up the directory tree for configuration in the following places:
.soursocksrcfile in JSON or YAML format
soursocks.config.jsfile exporting a JS object
Cosmiconfig continues to search up the directory tree, checking each of these places in each directory, until it finds some acceptable configuration (or hits the home directory).
👀 Looking for the v4 docs?
v5 involves significant revisions to Cosmiconfig's API, allowing for much greater flexibility and clarifying some things.
If you have trouble switching from v4 to v5, please file an issue.
If you are still using v4, those v4 docs are available in the
Table of contents
- Differences from rc
- Contributing & Development
npm install cosmiconfig
Tested in Node 4+.
Create a Cosmiconfig explorer, then either
search for or directly
load a configuration file.
const cosmiconfig = ;// ...const explorer = ;// Search for a configuration by walking up directories.// See documentation for search, below.explorer;// 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;// You can also search and load synchronously.const searchedFor = explorer;const loaded = explorer;
The result object you get from
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.
trueif the configuration file is empty. This property will not be present if the configuration file is not empty.
const explorer =
Creates a cosmiconfig instance ("explorer") configured according to the arguments, and initializes its caches.
cosmiconfigOptions are documented below.
You may not need them, and should first read about the functions you'll use.
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
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 the
search()), look for configuration objects in the following places:
goldengrahamsproperty in a
.goldengrahamsrcfile with JSON or YAML syntax.
goldengrahams.config.jsJS file exporting the object.
- If none of those searches reveal a configuration object, move up one directory level and try again.
So the search continues in
../../../, etc., checking the same places in each directory.
- Continue searching until arriving at your home directory (or some other directory defined by the cosmiconfig option
- If at any point a parseable configuration is found, the
search()Promise resolves with its result (or, with
searchSync(), the result is returned).
- If no configuration object is found, the
search()Promise resolves with
- 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
searchSync(), the error is thrown.)
If you know exactly where your configuration file should be, you can use
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.
const result = explorer;
Synchronous version of
Returns a result or
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).
load if you already know where the configuration file is and you just need to load it.
explorer; // 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
const result = explorer;
Synchronous version of
Returns a result.
Clears the cache used in
Clears the cache used in
Default: See below.
An array of places that
search() will check in each directory as it moves up the directory tree.
Each place is relative to the directory being searched, and the places are checked in the specified order.
Create your own array to search more, fewer, or altogether different places.
package.json is a special value: When it is included in
searchPlaces, Cosmiconfig will always parse it as JSON and load a property within it, not the whole file.
That property is defined with the
packageProp option, and defaults to your module name.
Examples, with a module named
// Disallow extensions on rc files:'package.json''.porgyrc''porgy.config.js'// ESLint searches for configuration in these places:'.eslintrc.js''.eslintrc.yaml''.eslintrc.yml''.eslintrc.json''.eslintrc''package.json'// Babel looks in fewer places:'package.json''.babelrc'// Maybe you want to look for a wide variety of JS flavors:'porgy.config.js''porgy.config.mjs''porgy.config.ts''porgy.config.coffee'// ^^ You will need to designate custom loaders to tell// Cosmiconfig how to handle these special JS flavors.// Look within a .config/ subdirectory of every searched directory:'package.json''.porgyrc''.config/.porgyrc''.porgyrc.json''.config/.porgyrc.json'
Default: See below.
An object that maps extensions to the loader functions responsible for loading and parsing files with those extensions.
Cosmiconfig exposes its default loaders for
'.json': cosmiconfigloadJson'.yaml': cosmiconfigloadYaml'.yml': cosmiconfigloadYaml'.js': cosmiconfigloadJsnoExt: cosmiconfigloadYaml
(YAML is a superset of JSON; which means YAML parsers can parse JSON; which is how extensionless files can be either YAML or JSON with only one parser.)
If you provide a
loaders object, your object will be merged with the defaults.
So you can override one or two without having to override them all.
loaders are extensions (starting with a period), or
noExt to specify the loader for files without extensions, like
loaders are either a loader function (described below) or an object with
async properties, whose values are loader functions.
The most common use case for custom loaders value is to load extensionless
rc files as strict JSON, instead of JSON or YAML (the default).
To accomplish that, provide the following
If you want to load files that are not handled by the loader functions Cosmiconfig exposes, you can write a custom loader function or use one from NPM if it exists.
Use cases for custom loader function:
- Allow configuration syntaxes that aren't handled by Cosmiconfig's defaults, like JSON5, INI, or XML.
- Allow ES2015 modules from
- Parse JS files with Babel before deriving the configuration.
Custom loader functions have the following signature:
// SyncObject | null// AsyncObject | null | Promise<Object | null>
Cosmiconfig reads the file when it checks whether the file exists, so it will provide you with both the file's path and its content.
Do whatever you need to, and return either a configuration object or
null (or, for async-only loaders, a Promise that resolves with one of those).
null indicates that no real configuration was found and the search should continue.
It's easiest if you make your custom loader function synchronous.
Then it can be used regardless of whether you end up calling
If you want or need to provide an async-only loader, you can do so by making the value of
loaders an object with an
async property whose value is the async loader.
You can also add a
sync property to designate a sync loader, if you want to use both async and sync search and load functions.
A few things to note:
- If you use a custom loader, be aware of whether it's sync or async and how that aligned with your usage of sync or async search and load functions.
- Special JS syntax can also be handled by using a
require. Whether you use custom loaders or a
requirehook is up to you.
// Allow JSON5 syntax:'.json': json5Loader// Allow XML, and treat sync and async separately:'.xml': async: asyncXmlLoader sync: syncXmlLoader// Allow a special configuration syntax of your own creation:'.special': specialLoader// Allow many flavors of JS, using custom loaders:'.mjs': esmLoader'.ts': typeScriptLoader'.coffee': coffeeScriptLoader// Allow many flavors of JS but rely on require hooks:'.mjs': cosmiconfigloadJs'.ts': cosmiconfigloadJs'.coffee': cosmiconfigloadJs
Name of the property in
package.json to look for.
Default: Absolute path to your home directory.
Directory where the search will stop.
false, no caches will be used.
Read more about "Caching" below.
(Result) => Promise<Result> | Result.
A function that transforms the parsed configuration. Receives the result.
load() (which are async), the transform function can return the transformed result or return a Promise that resolves with the transformed result.
loadSync(), the function must be synchronous and return the transformed result.
The reason you might use this option — instead of simply applying your transform function some other way — is that the transformed result will be cached. If your transformation involves additional filesystem I/O or other potentially slow processing, you can use this option to avoid repeating those steps every time a given configuration is searched or loaded.
By default, if
search() encounters an empty file (containing nothing but whitespace) in one of the
searchPlaces, it will ignore the empty file and move on.
If you'd like to load empty configuration files, instead, set this option to
Why might you want to load empty configuration files? If you want to throw an error, or if an empty configuration file means something to your program.
As of v2, cosmiconfig uses caching to reduce the need for repetitious reading of the filesystem or expensive transforms. Every new cosmiconfig instance (created with
cosmiconfig()) has its own caches.
To avoid or work around caching, you can do the following:
- Set the
- Use the cache-clearing methods
- Create separate instances of cosmiconfig (separate "explorers").
rc serves its focused purpose well. cosmiconfig differs in a few key ways — making it more useful for some projects, less useful for others:
- Looks for configuration in some different places: in a
package.jsonproperty, an rc file, a
.config.jsfile, and rc files with extensions.
- Built-in support for JSON, YAML, and CommonJS formats.
- Stops at the first configuration found, instead of finding all that can be found up the directory tree and merging them automatically.
- Asynchronous by default (though can be run synchronously).
Contributing & Development
Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.
And please do participate!