-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
68 lines (46 loc) · 1.36 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
56
57
58
59
60
61
62
63
64
65
66
67
68
var readFormats = require('parse-formats');
var writeFormats = require('stringify-formats');
var path = require('path');
var initialOpts = {
readFormats: readFormats,
writeFormats: writeFormats,
ext: '',
encoding: 'utf8',
}
module.exports = coherent;
function coherent(filename, opts) {
// Make sure we're constructing a new object
if( Object.keys(this).length > 0 ) {
return new coherent(filename, opts);
}
this._opts = Object.assign({}, initialOpts, opts);
this._path = findPathWithExt(filename+this._opts.ext);
this._opts.ext = path.extname(this._path);
return this;
}
coherent.prototype.read = require('./read.js');
coherent.prototype.write = require('./write.js');
module.exports.read = function(path, opts) {
return coherent(path).read(opts);
}
module.exports.write = function(path, data, opts) {
return coherent(path).write(data, opts);
}
function findPathWithExt(file) {
var exists = require('fs').accessSync; // Throws on failure
// Check if a supported ext is already present
var presentExt = path.extname(file);
if( readFormats[presentExt] ) {
return file;
}
// Try each ext until we find a file
var readExts = Object.keys(readFormats);
for (var ext of readExts) {
try {
exists(file+ext);
} catch(e) { continue; }
return file+ext;
}
// If none found just assume we're creating a .json file
return file+'.json';
}