Convert Blob data to Raw buffer in javascript or node

31,328

Solution 1

For me, it worked with the following:

const buffer=Buffer.from(blob,'binary');

So, this buffer can be stored in Google Cloud Storage and local disk with fs node package.

I used blob file, to send data from client to server through ddp protocol (Meteor), so, when this file arrives to server I convert it to buffer in order to store it.

Solution 2

           var blob = new Blob([array], {type: "application/pdf"});

            var arrayBuffer, uint8Array;
            var fileReader = new FileReader();
            fileReader.onload = function() {
                arrayBuffer = this.result;
                uint8Array  = new Uint8Array(arrayBuffer);

                var printer = require("./js/controller/lib");
                printer.printDirect({
                    data: uint8Array,
                    printer:'Deskjet_3540',
                    type: 'PDF',
                    success: function(id) {
                        console.log('printed with id ' + id);
                    },
                    error: function(err) {
                        console.error('error on printing: ' + err);
                    }
                })
            };
            fileReader.readAsArrayBuffer(blob);

This is the final code which worked for me. The printer accepts uint8Array encoding format.

Solution 3

If you are not using NodeJS then you should know that the browser does not have a Buffer class implementation and you are probably compiling your code to browser-specific environment on something like browserify. In that case you need this library that converts your blob into a Buffer class that is supposed to be as perfectly equal to a NodeJS Buffer object as possible (the implementation is at feross/buffer).

If you are using node-fetch (not OP's case) then you probably got a blob from a response object:

const fetch = require("node-fetch");
const response = await fetch("http://www.stackoverflow.com/");
const blob = await response.blob();

This blob is an internal implementation and exists only inside node-fetch or fetch-blob libraries, to convert it to a native NodeJS Buffer object you need to transform it to an arrayBuffer first:

const arrayBuffer = await blob.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);

This buffer object can then be used on things such as file writes and server responses.

Share:
31,328
Kamaldeep Singh
Author by

Kamaldeep Singh

Updated on July 09, 2022

Comments

  • Kamaldeep Singh
    Kamaldeep Singh almost 2 years

    I am using a plugin jsPDF which generates PDF and saves it to local file system. Now in jsPDF.js, there is some piece of code which generates pdf data in blob format as:-

    var blob = new Blob([array], {type: "application/pdf"});
    

    and further saves the blob data to local file system. Now instead of saving I need to print the PDF using plugin node-printer.

    Here is some sample code to do so

    var fs = require('fs'),
    var dataToPrinter;
    
    fs.readFile('/home/ubuntu/test.pdf', function(err, data){
        dataToPrinter = data;
    }
    
    var printer = require("../lib");
    printer.printDirect({
        data: dataToPrinter,
        printer:'Deskjet_3540',
        type: 'PDF',
        success: function(id) {
            console.log('printed with id ' + id);
        },
        error: function(err) {
            console.error('error on printing: ' + err);
        }
    })
    

    The fs.readFile() reads the PDF file and generates data in raw buffer format.

    Now what I want is to convert the 'Blob' data into 'raw buffer' so that I can print the PDF.

  • Kamaldeep Singh
    Kamaldeep Singh over 8 years
    What does this "binary" denote ? Is this the type format of buffer ?
  • Alexandr Lazarev
    Alexandr Lazarev over 8 years
    It specifies the encoding of the input string.
  • Kamaldeep Singh
    Kamaldeep Singh over 8 years
    You mean to say here 'array' is of "application/pdf" format and what 'blob' is generated is of "binary" format.
  • Alexandr Lazarev
    Alexandr Lazarev over 8 years
    BLOB(Binary Large OBject) is a collection of binary data stored in an entity. In your particular case, this entity is a string. If you want to create a buffer from that string, you should specify it's encoding int buffer constructor function. That is what I mean :)
  • Kamaldeep Singh
    Kamaldeep Singh over 8 years
    Ok what other formats does BLOB supports ? And particularly where and in what scenarios are these blob and buffer are used. What is difference between them in simple terms. Actually I am new to this encoding and decoding techniques. So its shaking my head. Would be thankful if you provide me some helpful link from where I can learn about them in detail and perform encoding and decoding as per my need in future.
  • Alexandr Lazarev
    Alexandr Lazarev over 8 years
  • Kamaldeep Singh
    Kamaldeep Singh over 8 years
    Today after reaching back to my work place I tested the solution with my printer but the buffer data which I provide to printer is putting the printing job on hold. Please look into this what else I could try out
  • Kamaldeep Singh
    Kamaldeep Singh over 8 years
  • sixtyfootersdude
    sixtyfootersdude about 6 years
    This doesn't seem to work on NodeJs. I am getting an error: Argument of type 'Blob' is not assignable to parameter of type 'string'.
  • Terry Windwalker
    Terry Windwalker over 2 years
    Tried this and receive TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received an instance of Blob
  • Noelle L.
    Noelle L. almost 2 years
    @TerryWindwalker Try await blob.arrayBuffer().then((arrayBuffer) => Buffer.from(arrayBuffer, "binary"))