-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
55 lines (46 loc) · 1.07 KB
/
index.js
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
'use strict'
const path = require('path')
const fs = require('graceful-fs')
const isValidExt = (file) => {
if (path.extname(file) !== '.json') {
throw new Error('The path provided should end with .json')
}
return true
}
const isValidObj = (obj) => {
const valid = Object.prototype.toString.call(obj) === '[object Object]'
if (!valid) {
throw new Error('The object provided is invalid')
}
return true
}
/**
* Write to a JSON file sync
*/
module.exports.writeJSON = function (filename = 'file.json', obj = {}) {
isValidExt(filename)
isValidObj(obj)
try {
const data = JSON.stringify(obj)
fs.writeFileSync(filename, data)
return true
} catch (e) {
throw e
}
}
/**
* Read from a JSON file sync & parse the JSON
*/
module.exports.readJSON = function (filename = 'file.json') {
isValidExt(filename)
if (fs.existsSync(filename)) {
try {
const data = fs.readFileSync(filename, 'utf-8').trim() || {}
return JSON.parse(data)
} catch (e) {
throw e
}
} else {
throw new Error('The file does not exist')
}
}