Ali
Ali

Reputation: 25

append JSON parsing from XML using NodeJS

I have three different sample.xml files which I have to convert into json output. I am trying to append all of their output into one json file. here is my code

const fs = require('fs');
const xml2js = require('xml2js');

parser = new xml2js.Parser({
    explicitArray: true
})
fs.readFile('sample.xml', (err, data) => {
    parser.parseString(data, (err, result) => {
        let output = JSON.stringify(result.planes.plane);
        fs.writeFile('output.json', output, 'utf8', (err) => {
            if (err) {
                throw err;
            } else {
                console.log('file created..')
            }
        })
    });

});

now I know the function fs.appendfile() but I am not sure how do I do it? I have two more files named: sample2.xml and sample3.xml

this is what I have tried but the problem it is overwriting not appending.

const fs = require('fs');
const xml2js = require('xml2js');
const async = require('async');
parser = new xml2js.Parser({
    explicitArray: true
})
let files = ['sample.xml', 'sample2.xml'];
async.map(files, fs.readFile, (err, files) => {
    if (err) {
        throw err;
    } else {
        files.forEach((file) => {
            parser.parseString(file, (err, result) => {
                let output = JSON.stringify(result.planes.plane);
                fs.appendFile('output.json', output, 'utf8', (err) => {
                    if (err) {
                        throw err;
                    } else {
                        console.log('file created..')
                    }
                })
            });
        })
    }
})

Upvotes: 1

Views: 169

Answers (1)

stdob--
stdob--

Reputation: 29157

You need to read each xml file, get the json-data from it, and then write it to the final file:

async.map(
  files,
  (file, cb) => {
    fs.readFile(file, (err, data) => {
      if (err) {
        cb(err)
      } else {
        parser.parseString(data, (err, result) => {
          cb(err, result.planes.plane)
        })
      }
    })
  },
  function (err, results) {
    if (err) {
      throw err
    } else {
      let output = JSON.stringify(results)
      fs.writeFile('output.json', output, 'utf8', (err) => {
        if (err) {
          throw err
        } else {
          console.log('file created...')
        }
      })
    }
  }
)

Upvotes: 1

Related Questions