3

I'm migrating one website with java/jsf for Node/Angular but i have the problem for convert blob from firebird database to base64 using node-firebird.

connection.query(query,function(err,rows){

  if(err) {
    res.json({"Error" : true, "Message" : "Error executing query"});
  } else {

    var buffer;
    var bufferBase64;

    for(var i = 0; i < rows.length; i++){
      rows[i].image(function(err, name, eventEmitter) {

        eventEmitter.on('data', function(chunk) {
           buffer = new Buffer(chunk, 'binary').toString('base64');
           bufferBase64 += buffer;

        });
        eventEmitter.on('end', function() {
        console.log(bufferBase64); // print base64
        });
      });

    }

    res.json(rows);
  }
  connection.detach();
});

This code from node-firebird generate a invalid base64, but this work using Java.

byte[] encoded = Base64.getEncoder().encode(rs.getBytes("image"));
System.out.println(new String(encoded));

This is a buffers of a image : [function] that returns from the database

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Douglas
  • 71
  • 5
  • 1
    It is not clear to me what the problem is, the screenshots seems to be the raw bytes. If I had to guess, your problem is that you need to convert all bytes to a single base64 string, while currently you are encoding chunks to base64 individually and concatenating that, which could lead to base64 padding (`=`..) mid-string, instead of only at the end. That, or - I don't know node.js - that `toString` doesn't do what you think it does. – Mark Rotteveel Oct 05 '17 at 11:59
  • The problem is that I'm a beginner with javascript/node and I'm trying to learn, but I'm having trouble solving this part of reading the bytes and converting to base64. https://github.com/hgourvest/node-firebird#reading-blobs-asynchronous – Douglas Oct 05 '17 at 12:49
  • I just need to transform the code in java to javascript and print a base64. I can not get a valid base64 – Douglas Oct 05 '17 at 13:30
  • Maybe this question will help, seems to be a similar problem: https://stackoverflow.com/questions/46054531/nodejs-unable-to-convert-stream-buffer-to-base64-string – Mark Rotteveel Oct 05 '17 at 14:03
  • Thank you very much, it really solved my problem. – Douglas Oct 05 '17 at 14:40

1 Answers1

4

Thanks Mark rotteveel for solved my problem.

if have someone else with the same problem, below the solution.

         rows[i].image(function(err, name, eventEmitter) {
            let buffers = [];
            eventEmitter.on('data', function(chunk) {
               buffers.push(chunk);
            });
            eventEmitter.once('end', function() {
            let buffer = Buffer.concat(buffers);
            console.log(buffer.toString('base64')); // print base64
            });
          });
Douglas
  • 71
  • 5