Soumya Mohapatra
Soumya Mohapatra

Reputation: 85

res.send() not able to send entire base64 string to client

Basically, I'm trying to capture screenshots of websites and at the same time trying to store them into local storage of the browser. So I am taking help of webshot(which is an npm package and a light wrapper around phantomjs).But unfortunately, res.send() is not able to send the entire data to the client. That's why my image appears as only 25% of the original image, as it sends only some amount of the base64 encoded string. specificData which is the base64 encoded string of the actual buffer data fetched by webshot is not sent at whole over to the client. Below is my server side code

const express = require("express");
const app = express();


let webshot = require('webshot');
let specificData;

app.get('/',(req,res)=>{
    res.send("let's get started");
});

app.get('/imageViewer',(req,res)=>{
    res.sendFile(__dirname+'/index.html');
});

app.get('/storeImageToLocalStorage',(req,res,next)=>{
    let renderStream = webshot('stackoverflow.com');
    renderStream.on('data', function(data) {
        specificData=data.toString('base64');
        next();
    });
},(req,res)=>{
    res.send(specificData);
});

app.listen(5676,()=>{
console.log("listening at http://localhost:5676");});

Below is my index File which is sent when get request is received from the client. Then the specificData is fetched from the server which is actually a chunk received from the server end due to the shortcoming of res.send(). I have searched all over the net of how to fix this but I couldn't find any relevant solution. That is why I have turned to stackoverflow to get my question answered.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script
            src="https://code.jquery.com/jquery-3.2.1.js"
            integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
            crossorigin="anonymous">
    </script>
</head>
<body>
<img id="tableBanner" style="height: 40vh;width: 40vw">
<script>
    $(()=>{
        let bannerImg = document.getElementById('tableBanner');
        $.get('/storeImageToLocalStorage',(specificData)=>{
            localStorage.setItem('specificData',specificData);
            bannerImg.src = 'data:image/png;base64,'+localStorage.getItem('specificData');
        });

    });
</script>
</body>
</html>

Upvotes: 0

Views: 877

Answers (1)

wrangler
wrangler

Reputation: 3576

Thats because you are overwriting everytime data is received and passing to next middleware on first chunk of data receive:

renderStream.on('data', function(data) {
        specificData += data.toString('base64');  //append
});

//calling next() when data has stopped listening
renderStream.on('end', function() {
       next();
})

Upvotes: 1

Related Questions