edit-config
v1.8.0
Published
Read, edit, write configuration files.
Downloads
48
Maintainers
Readme
edit-config
Read, edit, write configuration files.
- Synopsis
- Details
- API
- edit-config
- Classes
- Class: DataFile ‹T›
- Class: Manager
- Interfaces
- Interface: DataFileFromDataOptions
- Interface: DataFileLoadOptions
- Interface: Logger
- Interface: ManagerFromDataOptions
- Interface: ManagerLoadOptions
Synopsis
Load, Edit & Save Single Config
import { DataFile, Manager } from "edit-config";
const packageJson = await DataFile.load("package.json");
packageJson
.set("typings", "dist/index.d.ts",")
.set("scripts.build", "tsc")
.set("scripts.test", (value) => `${value} --coverage`)
.merge("husky.hooks", { pre-commit: "eslint" })
.merge("devDependencies", (value, key, data, path, dataFile) => ({ "@types/lodash": dataFile.get("dependencies.lodash") }) )
.sortKeys("scripts", { start: ["build", "test", "lint"] });
await packageJson.save();
Cosmiconfig: Load, Edit & Save
// Loads from `package.json` or configuration file using cosmiconfig. Set true to use default cosmiconfig configuration.
const husky = await DataFile.load("husky", { cosmiconfig: true });
const eslint = await DataFile.load("eslint", { cosmiconfig: { options: cosmiconfigOptions, searchFrom: __dirname } });
husky.set("hooks.pre-commit", "lint-staged");
// Check if cosmiconfig data can be saved, because saving "js" files are not supported.
if (!husky.readOnly) await husky.save();
Load, Edit & Save Multiple Config
// Create manager and load files.
const manager = new Manager({ root: ".", logger: winstonLogger });
const [packageJson, tsconfig] = await manager.loadAll(["package.json", "tsconfig.json"]);
await manager.saveAll();
Example Logger
import { createLogger, format, transports } from "winston";
const logger = createLogger({
level: "debug",
format: format.combine(format.colorize(), format.splat(), format.simple()),
transports: [new transports.Console()],
});
const packageJson = await DataFile.load("package.json", { logger });
Conditional Update
const packageJson = await DataFile.load("package.json");
packageJson
.set("keywords", ["my", "keywords"], { if: (value) => value === undefined })
.merge("scripts", { build: "tsc", test: "jest" }, { if: (value, key, data, path, rootData) => rootData.has("typings") });
Details
DataFile
class reads JSON
, YAML
and JS
configuration files and writes JSON
and YAML
files. Manager
class is used to manage multiple DataFile
classes.
Tips
- Don't forget to add
await
when chainingasync
methods:await (await packageJson.reload()).save();
Highlights:
- Provides
has
,get
,set
,merge
methods based onlodash
functions.delete
is based onlodash.unset
. - In addition to lodash functionality, manipulation methods accept value function and condition callback function for conditional manipulation.
load()
andloadAll()
do not throw even files do not exist. Instead return default data (if provided), or empty object.- Data manipulation operations do not write to disk until
save()
orsaveAll()
called ifautoSave
isfalse
. (Default behaviour) Manager.load()
andManager.loadAll()
methods cache loaded files and return cached results in consequencing calls. UseDataFile.reload()
to reload from disk.- Supports
winston
logger.
API
edit-config
Type aliases
FileFormat
Ƭ FileFormat: "" | "json" | "yaml" | "js"
Defined in types.ts:12
Data file format.
LogLevel
Ƭ LogLevel: "error" | "warn" | "info" | "http" | "verbose" | "debug" | "silly"
Defined in types.ts:9
PredicateFunction
Ƭ PredicateFunction: function
Defined in types.ts:29
Type declaration:
▸ (value
: any, key
: Key, data
: object, path
: Key[], dataFile
: DataFile): boolean
Callback function to test whether operation should be performed. If result is false, operation is not performed.
Parameters:
Name | Type | Description |
------ | ------ | ------ |
value
| any | is the value to be modified. |
key
| Key | is the key of the changed value. |
data
| object | is the object/array to get value from. |
path
| Key[] | is the full data path of the value in root data. |
dataFile
| DataFile | is the DataFile instance. |
ValueFunction
Ƭ ValueFunction: function
Defined in types.ts:42
Type declaration:
▸ (value
: any, key
: Key, data
: object, path
: Key[], dataFile
: DataFile): any
If a function is provided instead of value, return value of the function is used as new value.
Parameters:
Name | Type | Description |
------ | ------ | ------ |
value
| any | is the value to be modified. |
key
| Key | is the key of the changed value. |
data
| object | is the object/array to get value from. |
path
| Key[] | is the full data path of the value in root data. |
dataFile
| DataFile | is the DataFile instance. |
WritableFileFormat
Ƭ WritableFileFormat: "json" | "yaml"
Defined in types.ts:15
Writeable Data file format.
Classes
Class: DataFile ‹T›
Read, edit and write configuration files.
Type parameters
▪ T: object
Hierarchy
- DataFile
Properties
data
• data: T
Defined in data-file.ts:45
Actual data
found
• found: boolean
Defined in data-file.ts:48
Whether file exists or cosmiconfig configuration found.
Accessors
readOnly
• get readOnly(): boolean
Defined in data-file.ts:100
Whether file can be saved using this library.
Returns: boolean
Methods
delete
▸ delete(path
: DataPath, __namedParameters
: object): this
Defined in data-file.ts:169
Deletes the property at path
of file data.
Example
dataFile
.delete("script.build")
.delete(["scripts", "test"], { if: (value) => value !== "jest" });
Parameters:
▪ path: DataPath
is data path of the property to delete.
▪Default value
__namedParameters: object= {}
Name | Type | Description |
------ | ------ | ------ |
condition
| undefined | function | - |
logger
| undefined | Logger | is winston compatible logger to be used when logging. |
Returns: this
get
▸ get(path
: DataPath, defaultValue?
: any): any
Defined in data-file.ts:129
Gets the value at path
of file data. If the resolved value is undefined, the defaultValue
is returned in its place.
Example
dataFile.get("script.build");
dataFile.get(["script", "build"]);
Parameters:
Name | Type | Description |
------ | ------ | ------ |
path
| DataPath | is data path of the property to get. |
defaultValue?
| any | is value to get if path does not exists on data. |
Returns: any
data stored in given object path or default value.
getModifiedKeys
▸ getModifiedKeys(__namedParameters
: object): object
Defined in data-file.ts:224
Returns deleted and modified keys (paths) in data file. Keys may be filtered by required condition.
Example
dataFile.getModifiedKeys({ include: "scripts", exclude: ["scripts.validate", "scripts.docs"] });
Parameters:
▪Default value
__namedParameters: object= {}
Name | Type | Description |
------ | ------ | ------ |
filter
| undefined | function | is a filter function to test whether to include key and type in result. |
Returns: object
set and deleted keys
deleted: StringDataPath[]
set: StringDataPath[]
has
▸ has(path
: DataPath): boolean
Defined in data-file.ts:114
Returns whether given path
exists in file data.
Example
dataFile.has("script.build");
dataFile.has(["script", "build"]);
Parameters:
Name | Type | Description |
------ | ------ | ------ |
path
| DataPath | is data path of the property to check. |
Returns: boolean
whether path exists.
merge
▸ merge(path
: DataPath, ...valuesAndOptions
: any[]): this
Defined in data-file.ts:196
This method is like assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.
If you would like merge root object (this.data
), use empty array []
as path, because undefined
, '' and null
are valid object keys.
Example
dataFile.merge("scripts", { build: "tsc", test: "jest", }, { if: (scripts) => scripts.build !== "someCompiler" });
dataFile.merge([], { name: "my-module", version: "1.0.0" });
Parameters:
Name | Type | Description |
------ | ------ | ------ |
path
| DataPath | is data path of the property to delete. |
...valuesAndOptions
| any[] | are objects to merge given path or a function which returns object to be merged. |
Returns: this
reload
▸ reload(): Promise‹this›
Defined in data-file.ts:380
Reload data from disk. If file is not present resets data to default data.
Returns: Promise‹this›
save
▸ save(__namedParameters
: object): Promise‹void›
Defined in data-file.ts:279
Saves file. If this is a partial data uses only related part by utilizing rootDataPath
option.
Parameters:
▪Default value
__namedParameters: object= {}
Name | Type | Default | Description |
------ | ------ | ------ | ------ |
logger
| Logger | this.#logger | Winston compatible logger to be used when logging. |
throwOnReadOnly
| boolean | true | Whether to throw if file is read only. |
Returns: Promise‹void›
serialize
▸ serialize(wholeFile
: boolean): Promise‹string›
Defined in data-file.ts:303
Returns data serialized as text.
Parameters:
Name | Type | Default | Description |
------ | ------ | ------ | ------ |
wholeFile
| boolean | false | is whether to serialize whole file when rootDataPath
is set. Reads whole file including rootDataPath
part and serializes whole file data. |
Returns: Promise‹string›
serialized data as string.
set
▸ set(path
: DataPath, value
: any, __namedParameters
: object): this
Defined in data-file.ts:147
Sets the value at path
of file data. If a portion of path doesn't exist, it's created.
Arrays are created for missing index properties while objects are created for all other missing properties.
Example
dataFile
.set("script.build", "tsc")
.set(["scripts", "test"], "jest", { if: (value) => value !== "mocha" });
Parameters:
▪ path: DataPath
is data path of the property to set.
▪ value: any
is value to set or a function which returns value to be set.
▪Default value
__namedParameters: object= {}
Name | Type | Description |
------ | ------ | ------ |
condition
| undefined | function | - |
logger
| undefined | Logger | is winston compatible logger to be used when logging. |
Returns: this
sortKeys
▸ sortKeys(path
: DataPath, __namedParameters
: object): this
Defined in data-file.ts:271
When keys/values added which are previously does not exist, they are added to the end of the file during file write. This method allows reordering of the keys in given path. Required keys may be put at the beginning and of the order.
If you would like sort root object (this.data
) use sort
method or, provide use empty array []
as path, because undefined
, '' and null
are valid object keys.
Example
dataFile.sortKeys("scripts", { start: ["build", "lint"], end: ["release"] });
dataFile.sortKeys({ start: ["name", "description"], end: ["dependencies", "devDependencies"] });
Parameters:
▪ path: DataPath
is data path of the property to order keys of.
▪Default value
__namedParameters: object= {}
Name | Type | Description |
------ | ------ | ------ |
end
| undefined | string[] | are ordered keys to appear at the end of given path when saved. |
start
| undefined | string[] | are ordered keys to appear at the beginning of given path when saved. |
Returns: this
Static
fromData
▸ fromData(path
: string, data
: object, options
: DataFileFromDataOptions): Promise‹DataFile›
Defined in data-file.ts:344
Creates DataFile instance from given data to be saved for given file path.
Parameters:
Name | Type | Default | Description |
------ | ------ | ------ | ------ |
path
| string | - | is path of the file. |
data
| object | - | is the data to create DataFile from. |
options
| DataFileFromDataOptions | {} | are options. |
Returns: Promise‹DataFile›
DataFile instance.
Static
load
▸ load(path
: string, options?
: DataFileLoadOptions): Promise‹DataFile›
Defined in data-file.ts:361
Reads data from given file. If file is not present returns default data to be saved with method.
throws
if file exists but cannot be parsed.
Parameters:
Name | Type | Description |
------ | ------ | ------ |
path
| string | is path of the file. |
options?
| DataFileLoadOptions | are options. |
Returns: Promise‹DataFile›
DataFile instance.
Class: Manager
Manage multiple configuration files using DataFile.
Hierarchy
- Manager
Constructors
constructor
+ new Manager(__namedParameters
: object): Manager
Defined in manager.ts:14
Creates a manager to manage multiple data files.
Parameters:
▪Default value
__namedParameters: object= {} as any
Name | Type | Default | Description |
------ | ------ | ------ | ------ |
logger
| Logger | noLogger | is the winston compatible Logger to be used when logging. |
root
| string | process.cwd() | is the root path to be used for all relative file paths. |
saveIfChanged
| undefined | false | true | - | is whether to save file only if data is changed. Clones initial data deeply to check during save. |
Returns: Manager
Methods
fromData
▸ fromData(path
: string, data
: object, options
: ManagerFromDataOptions): Promise‹DataFile›
Defined in manager.ts:67
Creates DataFile instance from given data and returns it. Also caches the data.
Parameters:
Name | Type | Default | Description |
------ | ------ | ------ | ------ |
path
| string | - | is the path of the file. Could be an absolute path or relative to root path option provided to Manager |
data
| object | - | is the data to create DataFile from. |
options
| ManagerFromDataOptions | {} | are options |
Returns: Promise‹DataFile›
DataFile instance.
load
▸ load(path
: string, options
: ManagerLoadOptions): Promise‹DataFile›
Defined in manager.ts:42
Reads data from given file and caches it. If file is not present, returns default data to be saved with DataFile.save or [[save]} methods. If same data file requested multiple times returns cached data file. Absolute path of the file is used as cache key.
Example
manager.load("package.json");
manager.load("eslint", { defaultFormat: "json", cosmiconfig: { options: { packageProp: "eslint" }, searchForm: "some/path" } })
Parameters:
Name | Type | Default | Description |
------ | ------ | ------ | ------ |
path
| string | - | is the path of the file. Could be an absolute path or relative to root path option provided to Manager. |
options
| ManagerLoadOptions | {} | are options |
Returns: Promise‹DataFile›
DataFile instance.
loadAll
▸ loadAll(paths
: string[], options
: object): Promise‹DataFile[]›
Defined in manager.ts:92
Reads data from all given files and caches them. If same data file requested multiple times returns cached data file. Absolute path of the file is used as cache key.
Parameters:
▪ paths: string[]
are arry of paths of the files. Could be an absolute path or relative to root path option provided to Manager.
▪Default value
options: object= {}
are options.
Name | Type | Description |
------ | ------ | ------ |
defaultData?
| any | is the default data to be used if file does not exist. |
defaultFormat?
| WritableFileFormat | is the default format to be used if file format cannot be determined from file name and content. |
readOnly?
| undefined | false | true | - |
saveIfChanged?
| undefined | false | true | is whether to save file only if data is changed. Clones initial data deeply to check during save. |
Returns: Promise‹DataFile[]›
saveAll
▸ saveAll(): Promise‹void›
Defined in manager.ts:102
Saves all files.
Returns: Promise‹void›
Interfaces
Interface: DataFileFromDataOptions
DataFile.fromData options.
Hierarchy
↳ DataFileFromDataOptions
Properties
Optional
defaultFormat
• defaultFormat? : WritableFileFormat
Inherited from ManagerFromDataOptions.defaultFormat
Defined in types.ts:58
The default format to be used if file format cannot be determined from file name and content.
Optional
logger
• logger? : Logger
Defined in types.ts:78
Winston compatible logger to be used when logging.
Optional
prettierConfig
• prettierConfig? : PrettierConfig
Defined in types.ts:82
Prettier configuration to be used. If not provided determined automatically.
Optional
readOnly
• readOnly? : undefined | false | true
Inherited from ManagerFromDataOptions.readOnly
Defined in types.ts:62
Whether file can be saved using this library.
Optional
rootDataPath
• rootDataPath? : DataPath
Inherited from ManagerFromDataOptions.rootDataPath
Defined in types.ts:60
If only some part of the data/config will be used, this is the data path to be used. For example if this is scripts
, only script
key of the data is loaded.
Optional
rootDir
• rootDir? : undefined | string
Defined in types.ts:80
Root directory for file. If provided, relative path is based on this root directory.
Optional
saveIfChanged
• saveIfChanged? : undefined | false | true
Inherited from ManagerFromDataOptions.saveIfChanged
Defined in types.ts:64
Whether to save file only if data is changed. Clones initial data deeply to check during save.
Interface: DataFileLoadOptions
[[DatFile.load]] options.
Hierarchy
↳ DataFileLoadOptions
Properties
Optional
cosmiconfig
• cosmiconfig? : boolean | object
Defined in types.ts:90
Whether to use https://www.npmjs.com/package/cosmiconfig to load configuration. Set true
for default cosmiconfig options or provide an object with options
for cosmiconfig options and searchFrom
to provide cosmiconfig.search()
parameter.
Optional
defaultData
• defaultData? : undefined | object
Defined in types.ts:88
If only some part of the data/config will be used, this is the data path to be used. For example if this is scripts
, only script
key of the data is loaded.
Optional
defaultFormat
• defaultFormat? : WritableFileFormat
Inherited from ManagerFromDataOptions.defaultFormat
Defined in types.ts:58
The default format to be used if file format cannot be determined from file name and content.
Optional
logger
• logger? : Logger
Inherited from DataFileFromDataOptions.logger
Defined in types.ts:78
Winston compatible logger to be used when logging.
Optional
prettierConfig
• prettierConfig? : PrettierConfig
Inherited from DataFileFromDataOptions.prettierConfig
Defined in types.ts:82
Prettier configuration to be used. If not provided determined automatically.
Optional
readOnly
• readOnly? : undefined | false | true
Inherited from ManagerFromDataOptions.readOnly
Defined in types.ts:62
Whether file can be saved using this library.
Optional
rootDataPath
• rootDataPath? : DataPath
Inherited from ManagerFromDataOptions.rootDataPath
Defined in types.ts:60
If only some part of the data/config will be used, this is the data path to be used. For example if this is scripts
, only script
key of the data is loaded.
Optional
rootDir
• rootDir? : undefined | string
Inherited from DataFileFromDataOptions.rootDir
Defined in types.ts:80
Root directory for file. If provided, relative path is based on this root directory.
Optional
saveIfChanged
• saveIfChanged? : undefined | false | true
Inherited from ManagerFromDataOptions.saveIfChanged
Defined in types.ts:64
Whether to save file only if data is changed. Clones initial data deeply to check during save.
Interface: Logger
Logger
Hierarchy
- Logger
Properties
log
• log: function
Defined in types.ts:6
Type declaration:
▸ (...args
: Array‹any›): any
Parameters:
Name | Type |
------ | ------ |
...args
| Array‹any› |
Interface: ManagerFromDataOptions
Manager.fromData options.
Hierarchy
ManagerFromDataOptions
Properties
Optional
defaultFormat
• defaultFormat? : WritableFileFormat
Defined in types.ts:58
The default format to be used if file format cannot be determined from file name and content.
Optional
readOnly
• readOnly? : undefined | false | true
Defined in types.ts:62
Whether file can be saved using this library.
Optional
rootDataPath
• rootDataPath? : DataPath
Defined in types.ts:60
If only some part of the data/config will be used, this is the data path to be used. For example if this is scripts
, only script
key of the data is loaded.
Optional
saveIfChanged
• saveIfChanged? : undefined | false | true
Defined in types.ts:64
Whether to save file only if data is changed. Clones initial data deeply to check during save.
Interface: ManagerLoadOptions
Manager.load options.
Hierarchy
↳ ManagerLoadOptions
Properties
Optional
cosmiconfig
• cosmiconfig? : boolean | object
Defined in types.ts:72
Whether to use https://www.npmjs.com/package/cosmiconfig to load configuration. Set true
for default cosmiconfig options or provide an object with options
for cosmiconfig options and searchFrom
to provide cosmiconfig.search()
parameter.
Optional
defaultData
• defaultData? : any
Defined in types.ts:70
The default data to be used if file does not exist.
Optional
defaultFormat
• defaultFormat? : WritableFileFormat
Inherited from ManagerFromDataOptions.defaultFormat
Defined in types.ts:58
The default format to be used if file format cannot be determined from file name and content.
Optional
readOnly
• readOnly? : undefined | false | true
Inherited from ManagerFromDataOptions.readOnly
Defined in types.ts:62
Whether file can be saved using this library.
Optional
rootDataPath
• rootDataPath? : DataPath
Inherited from ManagerFromDataOptions.rootDataPath
Defined in types.ts:60
If only some part of the data/config will be used, this is the data path to be used. For example if this is scripts
, only script
key of the data is loaded.
Optional
saveIfChanged
• saveIfChanged? : undefined | false | true
Inherited from ManagerFromDataOptions.saveIfChanged
Defined in types.ts:64
Whether to save file only if data is changed. Clones initial data deeply to check during save.