1

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..')
                    }
                })
            });
        })
    }
})

1 Answer 1

1

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...')
        }
      })
    }
  }
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.