I think you are converting the data a bit more than you need to. Once you create the buffer with the proper encoding, you just need to write the buffer to the file.
var base64Data = req.rawBody.replace(/^data:image\/png;base64,/, "");
require("fs").writeFile("out.png", base64Data, 'base64', function(err) {
console.log(err);
});
new Buffer(…, ‘base64’) will convert the input string to a Buffer, which is just an array of bytes, by interpreting the input as a base64 encoded string. Then you can just write that byte array to the file.
Update
As mentioned in the comments, req.rawBody
is no longer a thing. If you are using express
/connect
then you should use the bodyParser()
middleware and use req.body
, and if you are doing this using standard Node then you need to aggregate the incoming data
event Buffer
objects and do this image data parsing in the end
callback.