4

I have a jrmxl (Jasper report) file stored in a postgresql database in a binary format (bytea). I'm trying to read that file and convert it into a plain jrmxl (XML) file and save it on the disk.

Here is what i've tried so far

var fs = require('fs');
exports.saveFile = function (pg) {
  //pg is the postgres connection to query the db
  pg.query('Select data from data_file where id = 123', function (err, result) {
    if (err) {
      console.log(err);
      return;
    }

    var data = result.rows[0].data;

    //Buffer.isBuffer(data) === true

    // I can get the data here. Now I try to convert it into text
    var file = data.toString('utf8');

    fs.writeFile('report.jrxml',file, function (er) {
      if (er) {
        console.log('an error occurred while saving the file');
        return;
      }
      console.log('file saved');
    }} 
  });
}

If i run the code above, the file is saved but it's somehow binary. How can i convert this to a plain xml file in text format that i can import in ireport for example?

Alex K
  • 22,315
  • 19
  • 108
  • 236
diokey
  • 176
  • 1
  • 2
  • 12

2 Answers2

2

You might try going through a buffer first. I have used this technique to transform DB BLOBs into base64 strings.

var fileBuffer = new Buffer( result.rows[0].data, 'binary' );
var file = fileBuffer.toString('utf8');
Nicolás Alarcón Rapela
  • 2,714
  • 1
  • 18
  • 29
clay
  • 5,917
  • 2
  • 23
  • 21
  • I had an issue with Dropbox JS SDK `filesDownload` and this helped to convert a string from `binary` to `utf-8`. – doup Jul 21 '17 at 15:49
0

I use 'pako' npm package to resolve that issue:

import { connection, Message } from 'websocket';
import * as pako from 'pako';

protected async onCustomMessage(message: Message, con): Promise<void> {
    let data;
    let text;
    if (message.type === 'utf8') {
      // console.log("Received UTF8: '" + message.utf8Data + "'");
      text = message.utf8Data;
      data = JSON.parse(text);
    } else {
      const binary = message.binaryData;

      text = pako.inflate(binary, {
        to: 'string',
      });
      data = JSON.parse(text);
    }
}

npm i pako && npm i -D @types/pako

Pax Beach
  • 2,059
  • 1
  • 20
  • 27