aboutsummaryrefslogtreecommitdiff
path: root/node_modules/write-json-file/index.js
blob: cbd7e706a01b1b7aa9a92a0942dd8c23f8d371ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'use strict';
const path = require('path');
const fs = require('graceful-fs');
const writeFileAtomic = require('write-file-atomic');
const sortKeys = require('sort-keys');
const makeDir = require('make-dir');
const pify = require('pify');
const detectIndent = require('detect-indent');

const init = (fn, fp, data, opts) => {
	if (!fp) {
		throw new TypeError('Expected a filepath');
	}

	if (data === undefined) {
		throw new TypeError('Expected data to stringify');
	}

	opts = Object.assign({
		indent: '\t',
		sortKeys: false
	}, opts);

	if (opts.sortKeys) {
		data = sortKeys(data, {
			deep: true,
			compare: typeof opts.sortKeys === 'function' && opts.sortKeys
		});
	}

	return fn(fp, data, opts);
};

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});
		});
};

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});
	init(mainSync, fp, data, opts);
};