UNPKG

1.39 kBJavaScriptView Raw
1const fs = require('fs-extra');
2const path = require('path');
3const jsondiff = require('jsondiffpatch');
4const getValue = require('./get-value');
5
6module.exports = config => {
7 function exportDataSync(file, value) {
8 const filename = path.join(config.path, file.getValue());
9 const output = getValue(value);
10
11 // Write to disk. Fat-arrow because we simply want the parent scope vars
12 const write = () => {
13 fs.ensureDirSync(path.dirname(filename));
14 fs.writeFileSync(filename, JSON.stringify(output, null, ' '));
15 // console.log(`${filename} saved.`);
16 };
17
18 // It is recommended to fs.readFile() and handle error if not exists instead of fs.exists
19 let existingdata;
20
21 try {
22 existingdata = fs.readFileSync(filename, 'utf8');
23 } catch (readerr) {
24 // If the file does not exist just write file
25 if (readerr && readerr.code === 'ENOENT') {
26 write();
27 }
28 }
29
30 if (!existingdata) {
31 write();
32 } else {
33 // Convert existing string to object, and then compare
34 const existingObject = JSON.parse(existingdata);
35 // If there is no difference, then simply return and do not write file
36 if (!jsondiff.diff(existingObject, output)) {
37 return value;
38 }
39 // Otherwise write out the new, unique-values file
40 write();
41 }
42
43 return value;
44 }
45
46 return exportDataSync;
47};