/
read-json.js
80 lines (54 loc) · 1.74 KB
/
read-json.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
69
70
71
72
73
74
75
76
77
78
79
80
module.exports = {
friendlyName: 'Read JSON file',
description: 'Read and parse JSON file located at source path on disk into usable data.',
extendedDescription: 'Assumes file is encoded using utf8.',
sideEffects: 'cacheable',
inputs: {
source: {
description: 'Absolute path to the source file (if relative path is provided, will resolve path from current working directory).',
example: '/Users/mikermcneil/.tmp/foo.json',
required: true
}
},
exits: {
success: {
outputFriendlyName: 'JSON data',
outputDescription: 'The JSON data parsed from the source file.',
outputType: 'json'
},
doesNotExist: {
description: 'No file could be found at the provided `source` path.'
},
couldNotParse: {
description: 'Could not parse the file as JSON.'
},
isDirectory: {
description: 'The specified path pointed to a directory.'
}
},
fn: function (inputs, exits) {
// Import this pack.
var Filesystem = require('../');
// Attempt to read the file at the specified path.
Filesystem.read({
source: inputs.source
}).switch({
// Forward errors through the appropriate exits.
error: exits.error,
doesNotExist: exits.doesNotExist,
isDirectory: exits.isDirectory,
// If the file was successfully read...
success: function (contents){
// Attempt to parse the file contents as JSON.
var parsedData;
try {
parsedData = JSON.parse(contents);
} catch (err) {
return exits.couldNotParse(err);
}
// If the data was successfully parsed, push it through our `success` exit.
return exits.success(parsedData);
}
});//_∏_
}
};