Farhan Yaseen Farhan Yaseen - 3 years ago 169
Node.js Question

How to convert properties file to xml node.js

I have

properties File
and I want to convert it to
XML
by using
node.js
.I don't know how can I convert, please help me

Answer Source
const builder      = require('xmlbuilder');
const fs           = require('fs');
const path         = require('path');
const PROPS_FILE   = //PROPS_FILE_PATH;
const XML_FILE     = //XML_FILE_PATH;
let xml            = builder.create('resources');


let readFromPropsFile = function(){
    let promise = new Promise(function(resolve, reject){
        console.log(PROPS_FILE);
        const readline = require('readline');
        const rl = readline.createInterface({
          input: fs.createReadStream(path.resolve(__dirname,PROPS_FILE))
        });
        rl.on('line', (line) => {
          let keyValuePair = line.split('=');
        // converting key valur to XML
          convertToXML(keyValuePair[0], keyValuePair[1]);
        });
        rl.on('error', function(e) {
            console.log(e);
            reject(e);
            // something went wrong 
        });
        rl.on('close', function(line){
            console.log(`done reading file ${PROPS_FILE}.`);
            resolve();
        })
    });
    return promise;
}; 

let convertToXML= function(key, value){
    xml.ele('string', {'name': `${key}`}, `${value}`);
};

let writeInToXMLFile = function(){
    let promise = new Promise(function(resolve, reject){
        fs.writeFile(path.resolve(__dirname,XML_FILE) , xml, function (error) {
            if (error) {
                console.error(error);
                reject(new Error(error));
            } else {
                console.log(`file ${XML_FILE} saved `);
                resolve();
            }
        });
     });
    return promise;
}


 readFromPropsFile()
.then(writeInToXMLFile)
.catch((err)=>{ console.log(err) });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download