write-json-file
Advanced tools
Comparing version 2.1.0 to 2.2.0
45
index.js
@@ -8,4 +8,5 @@ 'use strict'; | ||
const pify = require('pify'); | ||
const detectIndent = require('detect-indent'); | ||
const main = (fn, fp, data, opts) => { | ||
const init = (fn, fp, data, opts) => { | ||
if (!fp) { | ||
@@ -31,14 +32,44 @@ throw new TypeError('Expected a filepath'); | ||
const json = JSON.stringify(data, opts.replacer, opts.indent); | ||
return fn(fp, data, opts); | ||
}; | ||
return fn(fp, `${json}\n`, {mode: opts.mode}); | ||
const readFile = fp => pify(fs.readFile)(fp, 'utf8').catch(() => {}); | ||
const main = (fp, data, opts) => { | ||
return (opts.detectIndent ? readFile(fp) : Promise.resolve()) | ||
.then(str => { | ||
const indent = str ? detectIndent(str).indent : opts.indent; | ||
const json = JSON.stringify(data, opts.replacer, indent); | ||
return pify(writeFileAtomic)(fp, `${json}\n`, {mode: opts.mode}); | ||
}); | ||
}; | ||
module.exports = (fp, data, opts) => | ||
makeDir(path.dirname(fp), {fs}) | ||
.then(() => main(pify(writeFileAtomic), fp, data, opts)); | ||
const mainSync = (fp, data, opts) => { | ||
let indent = opts.indent; | ||
if (opts.detectIndent) { | ||
try { | ||
const file = fs.readFileSync(fp, 'utf8'); | ||
indent = detectIndent(file).indent; | ||
} catch (err) { | ||
if (err.code !== 'ENOENT') { | ||
throw err; | ||
} | ||
} | ||
} | ||
const json = JSON.stringify(data, opts.replacer, indent); | ||
return writeFileAtomic.sync(fp, `${json}\n`, {mode: opts.mode}); | ||
}; | ||
module.exports = (fp, data, opts) => { | ||
return makeDir(path.dirname(fp), {fs}) | ||
.then(() => init(main, fp, data, opts)); | ||
}; | ||
module.exports.sync = (fp, data, opts) => { | ||
makeDir.sync(path.dirname(fp), {fs}); | ||
main(writeFileAtomic.sync, fp, data, opts); | ||
init(mainSync, fp, data, opts); | ||
}; |
{ | ||
"name": "write-json-file", | ||
"version": "2.1.0", | ||
"version": "2.2.0", | ||
"description": "Stringify and write JSON to a file atomically", | ||
@@ -36,2 +36,3 @@ "license": "MIT", | ||
"dependencies": { | ||
"detect-indent": "^5.0.0", | ||
"graceful-fs": "^4.1.2", | ||
@@ -38,0 +39,0 @@ "make-dir": "^1.0.0", |
@@ -46,2 +46,9 @@ # write-json-file [![Build Status](https://travis-ci.org/sindresorhus/write-json-file.svg?branch=master)](https://travis-ci.org/sindresorhus/write-json-file) | ||
##### detectIndent | ||
Type: `boolean`<br> | ||
Default: `false` | ||
Detect indentation automatically if the file exists. | ||
##### sortKeys | ||
@@ -48,0 +55,0 @@ |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
5497
59
84
6
+ Addeddetect-indent@^5.0.0
+ Addeddetect-indent@5.0.0(transitive)