Skip to content

Commit

Permalink
Make outputJson() mutation-proof
Browse files Browse the repository at this point in the history
Fixes #702
  • Loading branch information
RyanZim committed Mar 10, 2020
1 parent 9a52356 commit 1403506
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 21 deletions.
20 changes: 20 additions & 0 deletions lib/json/__tests__/output-json.test.js
Expand Up @@ -33,6 +33,26 @@ describe('json', () => {
})
})

it('should be mutation-proof', async () => {
const dir = path.join(TEST_DIR, 'this-dir', 'certanly-does-not', 'exist')
const file = path.join(dir, 'file.json')
assert(!fs.existsSync(dir), 'directory cannot exist')

const name = 'JP'
const data = { name }
const promise = fse.outputJson(file, data)
// Mutate data right after call
data.name = 'Ryan'
// now await for the call to finish
await promise

assert(fs.existsSync(file))
const newData = JSON.parse(fs.readFileSync(file, 'utf8'))

// mutation did not change data
assert.strictEqual(newData.name, name)
})

it('should support Promises', () => {
const file = path.join(TEST_DIR, 'this-dir', 'prob-does-not', 'exist', 'file.json')
assert(!fs.existsSync(file))
Expand Down
2 changes: 1 addition & 1 deletion lib/json/index.js
@@ -1,6 +1,6 @@
'use strict'

const u = require('universalify').fromCallback
const u = require('universalify').fromPromise
const jsonFile = require('./jsonfile')

jsonFile.outputJson = u(require('./output-json'))
Expand Down
25 changes: 5 additions & 20 deletions lib/json/output-json.js
@@ -1,27 +1,12 @@
'use strict'

const path = require('path')
const mkdir = require('../mkdirs')
const pathExists = require('../path-exists').pathExists
const jsonFile = require('./jsonfile')
const { stringify } = require('jsonfile/utils')
const { outputFile } = require('../output')

function outputJson (file, data, options, callback) {
if (typeof options === 'function') {
callback = options
options = {}
}
async function outputJson (file, data, options = {}) {
const str = stringify(data, options)

const dir = path.dirname(file)

pathExists(dir, (err, itDoes) => {
if (err) return callback(err)
if (itDoes) return jsonFile.writeJson(file, data, options, callback)

mkdir.mkdirs(dir, err => {
if (err) return callback(err)
jsonFile.writeJson(file, data, options, callback)
})
})
await outputFile(file, str, options)
}

module.exports = outputJson

0 comments on commit 1403506

Please sign in to comment.