-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcddalint.js
64 lines (49 loc) · 1.4 KB
/
cddalint.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
/***
Github: https://github.com/ampersand55/CddaTools/
Dependencies: https://www.npmjs.com/package/node-fetch
Usage: node cddalint.js file.json
***/
const fs = require('fs');
const fetch = require('node-fetch');
if (process.argv.length !== 3) {
console.log('usage: node', process.argv[1], 'file.json');
process.exit();
}
const jsonFile = process.argv[2];
if (!jsonFile.endsWith('.json')) {
console.log(jsonFile, 'does not end with ".json"');
process.exit();
}
if (!fs.existsSync(jsonFile)) {
console.log(jsonFile, 'does not exist');
process.exit();
}
let originalBody = '';
fs.readFile(jsonFile, 'utf8', fetchLinter);
function fetchLinter(error, body) {
if (error)
throw error;
JSON.parse(body); // to test if json file is properly formatted;
originalBody = body;
fetch('http://dev.narc.ro/tools/format/json_formatter.cgi', {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'data=' + encodeURIComponent(body)
})
.then(res => res.text())
.then(saveFile);
}
function saveFile(formattedJSON) {
formattedJSON = formattedJSON.replace(/\r?\n/g, '\r\n');
if (formattedJSON === originalBody) {
console.log(jsonFile, 'is already properly linted');
return;
}
fs.writeFile(jsonFile, formattedJSON, error => {
if (error)
throw error;
console.log(jsonFile, 'has been linted and saved successfully');
});
}