Q:

Nodejs image from readStream gets displayed but connection is still open for a minute or so

I'm trying to create a profile picture upload feature and I'm stuck on the retrieval part. The image gets downloaded in chunks, and once it gets rendered for some reason there's still a spinning icon next to the image in the network tab for 60seconds, it's like the image is downloaded and rendered but it still takes about a minute or a bit longer for it to finish loading in the network tab of the browser, and if I try to upload another image in the mean time it doesn't get rendered until that minute or so of the previously uploaded image passes, could somebody help me figure this out please.
const storage = require('@google-cloud/storage');

const gcs = storage({
    projectId: 'my_project_id',
    keyFilename: 'keys.json'
});

const bucketName = 'my-profile-photos';
const bucket = gcs.bucket(bucketName);

const retrieveFromGcs = (req, res, next) => {
  const stream = bucket.file(req.params.name).createReadStream();

  res.writeHead(200, {'Content-Type': 'image/jpg' });

  stream.on('data', (data) => {
    console.log('hit stream on data');
    res.write(data);
  });

  stream.on('error', (err) => {
    console.log('hit error');
    next(err);
  });

  stream.on('finish', () => {
    console.log('hit finish');
    stream.end();
});

//in case the console.logs are useful for anyone, 'hit stream on data' gets printed around 200 times and 'hit finish' gets printed once

A:

Here when your streaming finish you have to end you res.
For that use below code
stream.on('finish', () => {
    console.log('hit finish');
    stream.end();
    res.end();
});

To complete the network loader. We must have to end our response object. So that browser know that there is no data to write in response now.

