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

I am trying to write canvas data using node.js as binary . The file is JPEG, but after the file is written, I see that the file is stored as plain text, not binary data. fs.writeFile fs.writeFile

This is an example datasent by the client to my site representing JPEG image data (just the first few characters):

/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAFA3PEY8MlBGQUZaVVBfeM...

I get these data on the client side by doing:

canvas.toDataURL('image/jpeg', 0.5).replace('data:image/jpeg;base64,', '')

Here is the use of the function on my node.js server :

fs.writeFile('../some.jpeg', data, 'binary', function(err){});

Instead of writing the file in binary form ( ๏ข–ืด๏ข–ืด๏ข– JFIF...), it records exactly the data that it received from the client.

What am I doing wrong here?

+11
3

JavaScript . Buffer API- Node.js, , TCP .

javascript, unicode-encoded, .

socket binary , unicode.

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 = new Buffer(data, 'base64');
fs.writeFile('image.png', buf);

+28

. , null "encoding" "request"

var request = require("request").defaults({ encoding: null });
var fs = require("fs");

fs.writeFile("./image.png", body, function(err) {
    if (err) throw err;
});
+3

Instead of writing the file directly to your client, first ask the server to send the images in binary format.

   let request= {
        headers: {
            'Content-Type': 'image/jpeg',
            'Authorization': "your token"
        },
        encoding:'binary'
    };
     request.get(url,request,(error, response, body)=>{
        if(error){
            console.log('error in get photo',error)
            return "default image to server";  
        }else{
            if(response.statusCode == 200){ 

      Fs.writeFile('path',body,'binary',function(err){
                    if(err){
                        return "your message";   
                    }else{
                        return "success";
                    }
                })
            }else{
                console.log('error in get photo 3')
                return "your message";  
            }
        }
    })
0
source

Source: https://habr.com/ru/post/1675118/


All Articles