UNPKG

1.51 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 exportData(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.ensureDir(path.dirname(filename), err => {
14 if (err) throw err;
15 fs.writeFile(filename, JSON.stringify(output, null, ' '), writeerr => {
16 if (writeerr) throw writeerr;
17 // console.log(`${filename} saved.`);
18 });
19 });
20 };
21
22 // It is recommended to fs.readFile() and handle error if not exists instead of fs.exists
23 fs.readFile(filename, 'utf8', (readerr, existingdata) => {
24 // If the file does not exist just write file
25 if (readerr && readerr.code === 'ENOENT') {
26 write();
27 }
28 // If there already exists data in the target file
29 if (existingdata) {
30 // Convert existing string to object, and then compare
31 const existingObject = JSON.parse(existingdata);
32 // If there is no difference, then simply return and do not write file
33 if (!jsondiff.diff(existingObject, output)) {
34 return value;
35 }
36 // Otherwise write out the new, unique-values file
37 write();
38 }
39 return value;
40 });
41
42 return value;
43 }
44 return exportData;
45};