2017-07-20 32 views

回答

0
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) });