Skip to content Skip to sidebar Skip to footer

How To Write Binary Data To A File Using Node.js?

I am trying to do toDataUrl() of canvas, and it gives base64 data. I want to store it as a png. I can get the converted binary data from base64, but I cant write it to a file usin

Solution 1:

You are making things much harder than they need to be. The node Buffer object takes base64 as input and does all of that decoding for you.

You can just strip the data:image... part from the base64 string and pass that data to your WriteFileAssistant.

var strData = this.drawingCanvas.getContext().canvas.toDataURL();
var imgData = strData.replace(/^data:image\/\w+;base64,/, "");
this.call(
  {
    filePath:'/media/internal/Collage/image.png',
    data: imgData
  },
  {
    method:"writeFile"
  }
);

The the WriteFileAssistant just needs to take the base64 string and pass that as an argument to the Buffer constructor. Also, having 'a+' on the openSync call will break things too.

varWriteFileAssistant = function(){};

WriteFileAssistant.prototype.run = function(future, subscription) {

  var fs = IMPORTS.require('fs');
  var filePath = this.controller.args.filePath;

  var fd =  fs.openSync('<path>/image.png', 'w');

  var buff = newBuffer(this.controller.args.data, 'base64');

  fs.write(fd, buff, 0, buff.length, 0, function(err,written){

  });
}

Buffer takes a string and an encoding, then it uses the encoding value to process the string into a series of bytes, so when you tell it that the string is base64, it will decode the base64 for you and create the proper decoded array of bytes to write to the file.

Post a Comment for "How To Write Binary Data To A File Using Node.js?"