Skip to content

Commit 24d119b

Browse files
kevvasindresorhus
authored andcommitted
Only sort keys on objects (#21)
1 parent 6a41819 commit 24d119b

File tree

3 files changed

+6
-1
lines changed

3 files changed

+6
-1
lines changed

index.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ const writeFileAtomic = require('write-file-atomic');
66
const sortKeys = require('sort-keys');
77
const makeDir = require('make-dir');
88
const detectIndent = require('detect-indent');
9+
const isPlainObj = require('is-plain-obj');
910

1011
const readFile = promisify(fs.readFile);
1112

@@ -24,7 +25,7 @@ const init = (fn, filePath, data, options) => {
2425
...options
2526
};
2627

27-
if (options.sortKeys) {
28+
if (options.sortKeys && isPlainObj(data)) {
2829
data = sortKeys(data, {
2930
deep: true,
3031
compare: typeof options.sortKeys === 'function' ? options.sortKeys : undefined

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
"dependencies": {
3737
"detect-indent": "^6.0.0",
3838
"graceful-fs": "^4.1.15",
39+
"is-plain-obj": "^2.0.0",
3940
"make-dir": "^3.0.0",
4041
"sort-keys": "^3.0.0",
4142
"write-file-atomic": "^3.0.0"

test.js

+3
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ test('async - {sortKeys: true}', async t => {
3939
const tempFile = tempy.file();
4040
await writeJsonFile(tempFile, {c: true, b: true, a: true}, {sortKeys: true});
4141
t.is(fs.readFileSync(tempFile, 'utf8'), '{\n\t"a": true,\n\t"b": true,\n\t"c": true\n}\n');
42+
43+
await writeJsonFile(tempFile, ['c', 'b', 'a'], {sortKeys: true});
44+
t.is(fs.readFileSync(tempFile, 'utf8'), '[\n\t"c",\n\t"b",\n\t"a"\n]\n');
4245
});
4346

4447
test('async - {sortKeys: false}', async t => {

0 commit comments

Comments
 (0)