Dhirish
Dhirish

Reputation: 351

Node.js, socket.io and base64-to-image not working

I am using node.js and socket.io to transfer an image from a server to a client. These are my codes ,

renderer.js:

const imgFile = fs.readFileSync(screenShotPath);
                    const imgFile64 = new Buffer(imgFile).toString('base64');
                    console.log("image data:"+ imgFile64);
                    socket.emit('img', imgFile64);

receiver.js:

    var base64ToImage = require('base64-to-image');
socket.on("img", function(info) {
    console.log("inside receiver");
    var base64Str = info;
    var path = 'path to file'; 
    var optionalObj = {'fileName': 'test', 'type':'png'};
    var imageInfo = base64ToImage(base64Str,path,optionalObj);
});

I am getting an error stating 'Invalid base64 string'. Can someone please help?

Upvotes: 0

Views: 1993

Answers (1)

Dushyant Bangal
Dushyant Bangal

Reputation: 6403

You can do that without base64-to-image

socket.on("img", function(info) {
    console.log("inside receiver");
    var base64Str = info;
    var buff = new Buffer(base64Str ,"base64");
    fs.writeFileSync("test.png", buff)
});

PS: On the server side, you don't have to do new Buffer(imgFile) because imgFile is already Buffer

Upvotes: 2

Related Questions