How to write binary data to a file using node.js?

前端 未结 1 1484
耶瑟儿~
耶瑟儿~ 2020-12-31 21:34

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 f

相关标签:
1条回答
  • 2020-12-31 21:53

    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.

    var WriteFileAssistant = 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 = new Buffer(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.

    0 讨论(0)
提交回复
热议问题