Home > database >  How to deal with xml file in next js?
How to deal with xml file in next js?

Time:03-02

i am trying to convert an xml file into json before create a response to return it to user. i getting this error message "You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders"

can someone point me out the right direction and tell me how to set this loader in next config if that's what needs to be done, please?

import xml2js from 'xml2js'
import {listing} from '../../listing.xml'


let parser = new  xml2js.Parser()
const data = () =>  parser.parseString(listing, function (err,result) {
  return result
}) 
console.log(data)
export default function handler(req, res) {
  res.status(200).send(JSON.stringify(data,null, 2))
}

CodePudding user response:

Since you are using API Route, these will be handled on the server-side, which means you are able to use Node APIs to read files and parse with xml2js lib

const parseString = require('xml2js').parseString;
const fs = require('fs');
const path = require('path');

export default (req, res) => {
  const data = fs.readFileSync(path.join(process.cwd(), 'note.xml'));
  parseString(data, function (err, result) {
    console.log(result);
    res.status(200).json({ result });
  });
};

https://nextjs-gkkygf--3000.local.webcontainer.io/api/xml

Full Stackblitz example

  • Related