Last active
May 24, 2017 20:00
-
-
Save rhagni/43a3d8fcbe7868035f8f00bd36fc307c to your computer and use it in GitHub Desktop.
Convert a YAML file to JSON using Nodejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
// npm install yamljs | |
const YAML = require("yamljs"); | |
const fs = require("fs"); | |
const readline = require("readline"); | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}); | |
if (process.argv.length < 3) { | |
console.log("Missing file operand"); | |
process.exit(1); | |
} | |
let queue = []; | |
let next = (() => { | |
let counter = 0; | |
return () => { | |
if (counter >= queue.length) { | |
return; | |
} | |
let actual = counter++; | |
queue[actual](); | |
queue[actual] = null; | |
} | |
})(); | |
for (let x = 2; x < process.argv.length; x++) { | |
queue.push(() => { | |
try { | |
let inputFile = process.argv[x]; | |
let yaml = fs.readFileSync(inputFile).toString(); | |
let outputFile = inputFile.replace(/(\.yaml|)$/, ".json"); | |
let parseYaml2JsonAndSave = () => { | |
let data; | |
try { | |
data = YAML.parse(yaml); | |
} catch (error) { | |
console.log(error); | |
process.exit(2); | |
// next(); | |
} | |
let json = JSON.stringify(data, null, " "); | |
try { | |
fs.writeFileSync(outputFile, json); | |
} catch (error) { | |
console.log(error); | |
process.exit(3); | |
// next(); | |
} | |
console.log(inputFile + " >>> " + outputFile); | |
next(); | |
}; | |
try { | |
fs.accessSync(outputFile); | |
rl.question( | |
"File '" + outputFile + "' already exists. Do you wanna overwrite? [y/N] ", | |
(input) => { | |
rl.pause(); | |
switch (input.toString().toLowerCase().trim()) { | |
case "y": | |
case "yep": | |
case "yes": | |
parseYaml2JsonAndSave(); | |
break; | |
default: | |
next(); | |
} | |
} | |
); | |
} catch (error) { | |
parseYaml2JsonAndSave(); | |
} | |
} catch (error) { | |
console.log(error); | |
next(); | |
} | |
}); | |
} | |
next(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment