Sanchit Kumar
Sanchit Kumar

Reputation: 45

JavaScript NodeJS Buffers

I am trying to make a client-server application where the client sends the server a list of filenames in an array such as let files = ["Cat.jpeg", "Moon.gif"] and I am trying to use Buffers so the server can send a response back to the client and open these files. But I am not sure how to approach this.

I tried

let imageNames = Buffer.from(files)

but I am not sure how to extract this and read these values.

Upvotes: 0

Views: 133

Answers (2)

Rohit Dalal
Rohit Dalal

Reputation: 866

I specifically would suggest instead of buffers use streams to pipeline the file in res individually.

Create a route which receives a filename, you stream down the file in the response.

In the front-end can make individual request for each file.

Because it will not overload the server and will increase its limit to handle a large number of requests in comparison to a single request doing heavy CPU utilization of all these files and returning response, for which Node.JS is really bad.

Upvotes: 1

Rhys Sharratt
Rhys Sharratt

Reputation: 39

An approach would be to return an array of BLOB objects (or buffers of the files that you have read from the server) back to the frontend and get the JS to convert the BLOBs/Buffers to the original file types for downloading.

Here's an example with PDFs that can easily be adapted:

Node:

// Express route
let fileBuffer = fs.fileReadSync('path/to/file.pdf')

return res.status(200).send(fileBuffer)

Frontend (React & Axios):

axios.get('api/endpoint')
  .then(response => {
    const pdfBlob = new Blob(
      [Response.data], 
      {type:'application/pdf;charset=utf8'}
    )

    // Save file here
  })
  .catch(error => {
    // do something with error
  })

Note The Blob API is part of the File API, which is in Working Draft and can change between browsers and versions. So ensure to do extensive browser testing.

Upvotes: 1

Related Questions