Dennis Wanyonyi
Dennis Wanyonyi

Reputation: 378

Express JS send array of files and json as response

I am trying to send back to the client an array of files, and a few more properties which are in json format as one response when a route is hit. I am relatively new to Node and Express but I have not found anyway to handle this. I know (and have successfully tried) sending one file back to the client. The kind of response I want to send back should look like this

res.send([
          {
            name:'Floral dresses',
            date_added:'2016-10-11 06:52:39',
            designer:'Victoria',
            cover_photo: path.join(__dirname, '/images', '/clothes', '/cloth1.jpg'),
            photos: [
              path.join(__dirname, '/images', '/clothes', '/cloth1.jpg'),
              path.join(__dirname, '/images', '/clothes', '/cloth2.jpg'),
              path.join(__dirname, '/images', '/clothes', '/cloth3.jpg')
            ]
          },
          {
            name:'Vintage Dresses',
            date_added:'2016-02-08 18:12:09',
            designer:'Victoria',
            cover_photo: path.join(__dirname, '/images', '/clothes', '/cloth1.jpg'),
            photos: [
              path.join(__dirname, '/images', '/clothes', '/cloth1.jpg'),
              path.join(__dirname, '/images', '/clothes', '/cloth2.jpg'),
              path.join(__dirname, '/images', '/clothes', '/cloth3.jpg')
            ]
          }
        ];

cover_photo and photos are images saved on the file system.

How can I achieve this in Node JS?

Upvotes: 3

Views: 2876

Answers (1)

robertklep
robertklep

Reputation: 203286

Since JSON isn't great to transfer (a lot of) binary data, I would suggest returning URL's to the image files, and having them served by Express.

Taking your directory setup, you'd add a static file handler:

app.use('/images', express.static(path.join(__dirname, 'images')));

For your JSON, the easiest then would be to pass the paths (relative to the website's root) to the image files, so the client can download them (or build a full URL and serve them in HTML).

For instance:

cover_photo: '/images/clothes/cloth1.jpg'

Upvotes: 4

Related Questions