Zidan
Zidan16mo ago

Closing a file

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()
}
}
)
)
}
)
}
);
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?
6 Replies
ioB
ioB16mo ago
If you use .readable, it's closed after the whole body is read automatically no need to manually close it
Zidan
ZidanOP16mo ago
oh, that's convenient got it, thanks 👍 file.stat appears to be a function that returns a promise now.. is there a way to get the file size in the same .then() or do i have to chain another .then?
ioB
ioB16mo ago
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()
}
}
)
)
}
);
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!
Zidan
ZidanOP16mo ago
and then check only the file open for erros i think?
ioB
ioB16mo ago
if you want to throw a better error, yes
Zidan
ZidanOP16mo ago
got it, thanks a lot