update-json-file

1.1.1 • Public • Published

update-json-file.js npm Travis CI Status

safely and conveniently edit the contents of a JSON file

Quick Example

const updateJsonFile = require('update-json-file')
 
const filePath = '/path/to/file/to/update.json'
 
updateJsonFile(filePath, (data) => {
  data.abc = 123
  return data
})

API

type Updater = (value: any) => any | Promise<any>

updateJsonFile = (
  filePath: string,
  updater: Updater,
  options?: any
) => Promise<void>
  • options pass through to write-json-file

  • by default, throws an error if the file does not already exist

  • "defaultValue" option swallows load/parse errors and calls updater as though file contained this value

  • "defaultValue" option can be a factory function, to help avoid mutation

  • your updater should avoid mutating the incoming data and return a clone instead (if necessary)

Examples

Avoiding mutation when defaultValue is the same object every time:

const updateJsonFile = require('update-json-file')
 
const filePath = '/path/to/file/to/update.json'
const options = { defaultValue: {} }
 
updateJsonFile(filePath, (data) => {
  // not safe to return `data`, need to return a modified clone
  return Object.assign({}, data, {
    abc: 123
  })
}, options)

Avoiding mutation by passing a factory function as defaultValue:

const updateJsonFile = require('update-json-file')
 
const filePath = '/path/to/file/to/update.json'
const options = { defaultValue: () => ({}) }
 
updateJsonFile(filePath, (data) => {
  // factory function is run each time, so `data` is a new object each time
  data.abc = 123
  return data
}, options)

See Also

Readme

Keywords

none

Package Sidebar

Install

npm i update-json-file

Weekly Downloads

3,060

Version

1.1.1

License

MIT

Last publish

Collaborators

  • jokeyrhyme