Home > Software engineering >  How to fetch xml content from sftp server with nodejs
How to fetch xml content from sftp server with nodejs

Time:05-13

I am going to fetch xml file content from SFTP server

let Client = require('ssh2-sftp-client');
let sftp = new Client();

 try {
      sftp.connect({
        host: 'hostname',
        port: '22',
        username: 'username',
        password: 'password'
    }).then(() => {
      return sftp.list('/outgoing/orders');
    }).then((dir) => {
      dir.forEach(element => {
        const xmlList = sftp.list('/outgoing/orders/'   element.name);
        xmlList.then(xml => {
          xml.forEach(xmlFile => {
            sftp.get('/outgoing/orders/'   element.name   '/'   xmlFile.name).then(xmlContent => {
              console.log(xmlContent)
            });
          })
        })
      });    
    })

<Buffer 3c 3f 78 6d 6c 20 76 65 72 73 69 6f 6e 3d 22 31 2e 30 22 3f 3e 0d 0a 3c 4f 72 64 65 72 4d 65 73 73 61 67 65 42 61 74 63 68 20 62 61 74 63 68 4e 75 6d ... 15509 more bytes>

Now it shows above console. How can I fetch content as xml format like this one?

<?xml version="1.0"?>
<OrderMessageBatch batchNumber="3012566157">
...

CodePudding user response:

Never used ssh2-sftp-client myself and I'm not sure if sftp.get(...) has a encoding parameter. But you always could decoding string from Buffer manually:

const xmlText = xmlContent.toString("utf8"); // change "utf8" to whatever encoding your file actually encoded with.
console.log(xmlText);

BTW, if the file is not encoded with a encoding natively supported by node, you may need packages like iconv or iconv-lite.

  • Related