Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
cosmiconfig
Advanced tools
Find and load configuration from a package.json property, rc file, or CommonJS module
The cosmiconfig npm package is a utility for finding and loading configuration from a variety of file formats and locations. It is commonly used in Node.js projects to create flexible configuration systems for tools and libraries.
Searching for configuration files
This feature allows you to search for configuration files with a given name in various locations, including package.json properties, rc files, and regular JSON or YAML files.
const cosmiconfig = require('cosmiconfig');
const explorer = cosmiconfig('yourModuleName');
explorer.search()
.then((result) => {
const config = result ? result.config : {};
// do something with config
})
.catch((error) => {
// handle error
});
Loading configuration files directly
This feature allows you to load a configuration file directly from a specified path, regardless of the file's format.
const cosmiconfig = require('cosmiconfig');
const explorer = cosmiconfig('yourModuleName');
explorer.load('/path/to/config').then((result) => {
const config = result ? result.config : {};
// do something with config
}).catch((error) => {
// handle error
});
Creating a custom explorer
This feature allows you to create a custom explorer with specific search places and loaders, enabling you to define where and how configuration files should be found and interpreted.
const cosmiconfig = require('cosmiconfig');
const explorer = cosmiconfig('yourModuleName', {
searchPlaces: ['custom.config.js', 'package.json'],
loaders: {
'.js': cosmiconfig.loadJs,
'.json': cosmiconfig.loadJson
}
});
The 'rc' package is similar to cosmiconfig in that it also searches for and loads configuration files. However, 'rc' focuses on a specific pattern of '.rc' files and does not support as many file formats as cosmiconfig.
The 'config' package is another configuration loader that supports multiple file formats. Unlike cosmiconfig, 'config' is designed for application configuration and has a different approach to file discovery, defaulting to a 'config' directory.
Convict is a configuration management library that includes schema definitions. It is more opinionated than cosmiconfig and includes validation and environment variable support out of the box, which cosmiconfig does not do without additional setup.
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 start where you tell it to start and search up the directory tree for the following:
package.json
property.json
, .yaml
, .yml
, or .js
..config.js
CommonJS moduleFor example, if your module's name is "soursocks", cosmiconfig will search up the directory tree for configuration in the following places:
soursocks
property in package.json
.soursocksrc
file in JSON or YAML format.soursocksrc.json
file.soursocksrc.yaml
, .soursocksrc.yml
, or .soursocksrc.js
filesoursocks.config.js
file exporting a JS objectCosmiconfig 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 4.0.0
tag.
npm install cosmiconfig
Tested in Node 4+.
Create a Cosmiconfig explorer, then either search
for or directly load
a configuration file.
const cosmiconfig = 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 searchedFor = explorer.searchSync();
const loaded = explorer.loadSync(pathToConfig);
The result object you get from search
or load
has the following properties:
undefined
if the file is empty.true
if the configuration file is empty. This property will not be present if the configuration file is not empty.const explorer = cosmiconfig(moduleName[, cosmiconfigOptions])
Creates a cosmiconfig instance ("explorer") configured according to the arguments, and initializes its caches.
Type: string
. Required.
Your module name. This is used to create the default searchPlaces
and packageProp
.
cosmiconfigOptions
are documented below.
You may not need them, and should first read about the functions you'll use.
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 searchSync()
.
Let's say your module name is goldengrahams
so you initialized with const explorer = cosmiconfig('goldengrahams');
.
Here's how your default search()
will work:
process.cwd()
(or some other directory defined by the searchFrom
argument to search()
), look for configuration objects in the following places:
goldengrahams
property in a package.json
file..goldengrahamsrc
file with JSON or YAML syntax..goldengrahamsrc.json
file..goldengrahamsrc.yaml
, .goldengrahamsrc.yml
, or .goldengrahamsrc.js
file.goldengrahams.config.js
JS file exporting the object../
, ../
, ../../
, ../../../
, etc., checking the same places in each directory.stopDir
).search()
Promise resolves with its result (or, with searchSync()
, the result is returned).search()
Promise resolves with null
(or, with searchSync()
, null
is returned).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 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.
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.
const result = explorer.searchSync([searchFrom]);
Synchronous version of search()
.
Returns a result or null
.
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
.
const result = explorer.loadSync(loadPath);
Synchronous version of load()
.
Returns a result.
Clears the cache used in load()
.
Clears the cache used in search()
.
Performs both clearLoadCache()
and clearSearchCache()
.
Type: Array<string>
.
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.
Default searchPlaces
:
[
'package.json',
`.${moduleName}rc`,
`.${moduleName}rc.json`,
`.${moduleName}rc.yaml`,
`.${moduleName}rc.yml`,
`.${moduleName}rc.js`,
`${moduleName}.config.js`,
]
Create your own array to search more, fewer, or altogether different places.
Every item in searchPlaces
needs to have a loader in loaders
that corresponds to its extension.
(Common extensions are covered by default loaders.)
Read more about loaders
below.
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 porgy
:
// 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'
]
Type: Object
.
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 .js
, .json
, and .yaml
as cosmiconfig.loadJs
, cosmiconfig.loadJson
, and cosmiconfig.loadYaml
, respectively.
Default loaders
:
{
'.json': cosmiconfig.loadJson,
'.yaml': cosmiconfig.loadYaml,
'.yml': cosmiconfig.loadYaml,
'.js': cosmiconfig.loadJs,
noExt: cosmiconfig.loadYaml
}
(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.
Keys in loaders
are extensions (starting with a period), or noExt
to specify the loader for files without extensions, like .soursocksrc
.
Values in loaders
are either a loader function (described below) or an object with sync
and/or 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 loaders
value:
{
noExt: cosmiconfig.loadJson
}
If you want to load files that are not handled by the loader functions Cosmiconfig exposes, you can write a custom loader function.
Use cases for custom loader function:
.mjs
configuration files.Custom loader functions have the following signature:
// Sync
(filepath: string, content: string) => Object | null
// Async
(filepath: string, content: string) => Object | 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 search()
or searchSync()
, load()
or loadSync()
.
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:
require
hook, because cosmiconfig.loadJs
just uses require
.
Whether you use custom loaders or a require
hook is up to you.Examples:
// 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': cosmiconfig.loadJs,
'.ts': cosmiconfig.loadJs,
'.coffee': cosmiconfig.loadJs
}
Type: string
.
Default: `${moduleName}`
.
Name of the property in package.json
to look for.
Type: string
.
Default: Absolute path to your home directory.
Directory where the search will stop.
Type: boolean
.
Default: true
.
If false
, no caches will be used.
Read more about "Caching" below.
Type: (Result) => Promise<Result> | Result
.
A function that transforms the parsed configuration. Receives the result.
If using search()
or load()
(which are async), the transform function can return the transformed result or return a Promise that resolves with the transformed result.
If using searchSync()
or 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.
Type: boolean
.
Default: true
.
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 false
.
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:
cosmiconfig
option cache
to false
.clearLoadCache()
, clearSearchCache()
, and clearCaches()
.rc serves its focused purpose well. cosmiconfig differs in a few key ways — making it more useful for some projects, less useful for others:
package.json
property, an rc file, a .config.js
file, and rc files with extensions.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!
5.0.5
load
and loadSync
work with paths relative to process.cwd()
.FAQs
Find and load configuration from a package.json property, rc file, TypeScript module, and more!
The npm package cosmiconfig receives a total of 34,836,251 weekly downloads. As such, cosmiconfig popularity was classified as popular.
We found that cosmiconfig demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.