How to do external file request NodeJS

0

How do I request an external file with NodeJS? In case it would be an XML ... link

    
asked by anonymous 21.11.2018 / 21:14

1 answer

1

You can do the following, use the link module to give get and convert path to xml > for an object . I created it as a promise so you can use await in an async function to wait for the get.

const http = require('http');
const xml2js = require('xml2js');
const parser = new xml2js.Parser();
const concat = require('concat-stream');

parser.on('error', function(err) { console.log('Parser error', err); });

const getXml = async()=>{
    return new Promise((resolve, reject) =>{
        http.get('http://179.127.4.122:8449/played.html?sid=1&type=xml', function(resp) {
            resp.on('error', function(err) {
                reject(err)
            })
            resp.pipe(concat(function(buffer) {
                const str = buffer.toString();
                parser.parseString(str, function(err, result) {
                    if(err){
                        reject(err);
                    }else{
                        console.log(result);
                        resolve(result);
                    }

                });
            }));

        });
    })
}

//export default getXml


async function init(){
    const data = await getXml()
    console.log(data);
}
init()
  

Reference

    
21.11.2018 / 22:22