update-json-file

safely and conveniently edit the contents of a JSON file

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
update-json-file
5121.1.16 years ago6 years agoMinified + gzip package size for update-json-file in KB

Readme

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>


  • 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