Writing binary data using node.js fs.writeFile to create an image file

前端 未结 4 642
渐次进展
渐次进展 2020-12-02 17:46

I\'m trying to write a canvas data with node.js fs.writeFile as a binary. JPEG file, but after the file is written I can see that the file is stored as plain text, not binar

4条回答
  •  甜味超标
    2020-12-02 18:33

    Use Buffer.from, as Buffer is deprecated, will get the following warning

    (node:15707) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.

    var fs = require('fs');
    // string generated by canvas.toDataURL()
    var img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0"
        + "NAAAAKElEQVQ4jWNgYGD4Twzu6FhFFGYYNXDUwGFpIAk2E4dHDRw1cDgaCAASFOffhEIO"
        + "3gAAAABJRU5ErkJggg==";
    // strip off the data: url prefix to get just the base64-encoded bytes
    var data = img.replace(/^data:image\/\w+;base64,/, "");
    var buf = Buffer.from(data, 'base64');
    fs.writeFile('image.png', buf);
    

提交回复
热议问题