Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js convert binary file to utf8

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?

like image 771
diokey Avatar asked Sep 15 '25 23:09

diokey


1 Answers

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');
like image 52
clay Avatar answered Sep 18 '25 16:09

clay