3

How do you send json together with an image file in express?

I understand you serve an image using res.sendFile

const path = require('path');

app.get('/image/:filename', (req, res, next) => {
  res.type('png');
  res.sendFile(
    path.resolve(`${path.join(__dirname, './data/images')}/${req.params.fileName}`)
  );
});

But then what if you want to include json with the image? For example if you are serving a user's profile data- name, info, etc and profile image.

const path = require('path');

app.get('/user/:id', async (req, res, next) => {
  const { id } = req.params;
  let user;
  try {
    user = await userService.getUser(id);
  } catch (err) {
    return next(err);
  }

  /* user:
   * {
   *   name: "Dash",
   *   location: "Chicago",
   *   profilePicture: '5c751e73-a7bc-47c4-b2a5-4ac902e7a2ce.png'
   * }
   */

  // what next????
});

You can't do

  res.type('png');
  res.sendFile(path.resolve(`${path.join(__dirname, './data/images')}/${user.profilePicture}`));

and res.send(json). So how do you send both?

1 Answer 1

6

Ideally, you don't.

JSON is a text-only format. If you want to include a binary resource in JSON, you would have to encode it with base64. This makes it compatible with text, but increases its size by 33%, while wasting CPU and memory for the encode and decode.

The usual method is to simply have two HTTP requests. There will be one to your Node.js API server, and another for the profile picture image. This is better for a lot of reasons. It solves your immediate problem, while also allowing you to host images outside of your application, and utilize CDNs and caching.

Sign up to request clarification or add additional context in comments.

1 Comment

And, of course, you can include the URL to the image in the JSON.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.