#Closing a file

9 messages · Page 1 of 1 (latest)

zealous coyote
#

How do I close a file after opening and streaming it?
My handler function code is as follows:

return new Promise(
  (grant) => {
    Deno.open(
      asset.path
    ).then(
      (file) => {
        grant(
          new Response(
            file.readable,
            {
              status: 200,
              headers: {
                "content-type": asset.type,
                "content-length": file.stat.size.toString()
              }
            }
          )
        )
      }
    )
  }
);

Is there a good way of closing the "file" after returning the "Response" object?

meager cedar
#

If you use .readable, it's closed after the whole body is read automatically

#

no need to manually close it

zealous coyote
#

oh, that's convenient
got it, thanks 👍

zealous coyote
meager cedar
#

I would have personally written this like

return new Promise(
  async (grant) => {
    const file = await Deno.open(
      asset.path
    );
    const stat = await file.stat();

    grant(
      new Response(
        file.readable,
        {
          status: 200,
          headers: {
            "content-type": asset.type,
            "content-length": file.stat.size.toString()
          }
        }
      )
    )
  }
);
#

async/await syntax is your friend!

zealous coyote
meager cedar
#

if you want to throw a better error, yes