-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·73 lines (67 loc) · 1.77 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
69
70
71
72
73
#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var program = require('commander');
program
.version('1.0.2')
.option('-f, --file <path>', 'JSON file path')
.parse(process.argv);
var files;
var currentFileIndex = 0;
var outputFolder = "pretty";
if( !program.file )
{
console.log( "JSON file path required. -h for help");
}else{
if( program.file == "all" )
{
var allFiles = fs.readdirSync("./");
files = [];
for (var i = 0; i < allFiles.length; i++) {
var rawFile = allFiles[i];
if( path.extname(rawFile) === ".json" ){
files.push( rawFile );
}
};
if( files.length == 0){
console.log( "No JSON files in current directory");
return;
}else{
console.log( "Will process all JSON files in current directory...");
}
}else{
files = [program.file];
}
// Check output folder exists
if ( !fs.existsSync(outputFolder)) {
console.log( "Output directory '" + outputFolder + "' does not exist. It will be created.")
fs.mkdirSync( outputFolder );
// Do something
}
readFile();
}
function readFile( )
{
var fileName = files[currentFileIndex];
console.log( fileName + ' (' + (currentFileIndex+1) + ' of ' + files.length + ')');
fs.readFile( fileName, 'utf8', function(err, data) {
if (err){
console.log( "ERROR reading: ", err );
return;
}
var jsonObj = JSON.parse(data);
var prettyJson = JSON.stringify( jsonObj, null, 4 );
fs.writeFile("./"+outputFolder+"/"+fileName, prettyJson, function(err) {
if(err) {
console.log("ERROR writing: ", err);
console.log( "Are you sure the provided Output directory ('" + outputFolder + "') exists?")
} else {
currentFileIndex++;
if( currentFileIndex < files.length )
{
readFile();
}
}
});
});
}