express icon indicating copy to clipboard operation
express copied to clipboard

[suggestion] send/respond with blob

Open jimmywarting opened this issue 2 years ago • 5 comments

NodeJS now has support for Blob's globally, ...earlier you had to load it from require('buffer').Blob

it would be cool / awesome if it where possible to respond with a Blob by doing something like

const str = `<h1>Hello World</h1>`
const blob = new Blob([str], { type: 'text/html' })
const file = new File([blob], 'index.html', { type: 'text/html' })

app.get('/', (req, res) => {
  res.send(blob) // or:
  res.download(blob, 'name.html')
  res.download(file) // name taken from file instead
})

Doing this would take care of

  1. Setting the response header content-type to the blob's type (only if content-type haven't been set manually)
  2. Setting the response header content-length to the blob's size
  3. and pipe the data from blob.stream() to the response
  4. if you used res.download(blob) then it would also add content-disposition attachment header

it's also looking like if node will at some point add a way of getting blobs from the filesystem also, but i don't know when. ref: https://github.com/nodejs/node/issues/39015

edit: NodeJS just shipped fs.openAsBlob(path, { type }) in v20+

jimmywarting avatar Feb 04 '22 12:02 jimmywarting

I think this is a great idea.

dougwilson avatar Feb 09 '22 22:02 dougwilson

Yeay, then I could take advantage of fetch-blob/from.js methods that can retrieve a Blob/File from the file system. or use undici or node-fetch await res.blob() even

If you would accept 3th party blob look-a-like objects ofc...

this idea came to me when i worked on a current project that uses a template engine. i just thought, wouldn't it be nice if consolidate.js or the static folder plugin could just simply give you a blob instead :P

var cons = require('consolidate');
cons.swig('views/page.html', function(err, blob){
  res.send(blob)
});

So if Blob are not the only thing you are going to support, then there is one extra idea coming from the File object and that is to send lastModifiedDate as a caching header. and also use the file.name when downloading using res.download(file)

jimmywarting avatar Feb 09 '22 22:02 jimmywarting

Hi @dougwilson , i want to take up this issue can you please assign me ?

debadutta98 avatar Nov 07 '22 05:11 debadutta98

fyi, NodeJS just shipped fs.openAsBlob(path, { type }) in v20+ wish I where able to use it now.

jimmywarting avatar May 29 '23 19:05 jimmywarting

No worries, there is a PR open that is very close to landing 👍 . Should be in the next Express release.

dougwilson avatar May 29 '23 19:05 dougwilson