Source: yaml2json.js

/** @fileOverview    
produces new file <filename>.json with filename contents in json format
if converting csv file, can add optional column name to use as key to make json map

Usage: node yaml2json.js (<filename>.yaml || <filename>.csv [column_for_key])");

@param <input_file> can be a .yaml file or a .csv file
@return <output_file> a file in JSON format with the same name but .json extension

*/


const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
const csv_parse = require('csv-parse/lib/sync');


if (process.argv.length < 3) {
    console.log("\n");
    console.log("Need to specify file to convert");
    console.log("\n");

    console.log("Usage: node yaml2json.js (<filename>.yaml || <filename>.csv [column_for_key])");
    console.log("produces new file <filename>.json with filename contents in json format");
    console.log("if converting csv file, can add optional column name to use as key to make json map")
    console.log("\n");
    process.exit(1);
}
var text_file_name = process.argv[2];

let key = null;

if (process.argv.length == 4){
    key = process.argv[3];
}

var dir = path.dirname(text_file_name);

console.log(dir);

var extension = ".yaml";

let text_type = "";


if (text_file_name.indexOf(".yaml") > 0 ) {
    extension = ".yaml";
    text_type = "yaml";
}
else if  (text_file_name.indexOf(".yml") > 0 ) {
    extension = ".yml";
    text_type = "yaml";

}
else if  (text_file_name.indexOf(".csv") > 0 ) {
    extension = ".csv";
    text_type = "csv";
}
else {
    console.log("Need a yaml or yml or csv extension!");
    exit(1);
}


var json_file_name = path.dirname(text_file_name) + "/" + path.basename(text_file_name,extension) + ".json";



console.log( text_file_name + " --> " + json_file_name);

var text_file_data;

if (text_type == "yaml") {
    text_file_data = yaml.safeLoad(fs.readFileSync(text_file_name, 'utf8'));
}
else if (text_type == "csv") {

    var text_csv = fs.readFileSync(text_file_name);
    
    if (null != key) {  text_file_data = csv_parse(text_csv, {'columns':true, 'objname': key});}
    else { text_file_data = csv_parse(text_csv, {'columns':true}); }
}
	
	

fs.writeFile(json_file_name, JSON.stringify(text_file_data, null, "\t"), function(err) {
if(err) {
   return console.log(err);
}});