Zidan
Zidan17mo 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
ioB17mo ago
If you use .readable, it's closed after the whole body is read automatically no need to manually close it
Zidan
ZidanOP17mo 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
ioB17mo 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
ZidanOP17mo ago
and then check only the file open for erros i think?
ioB
ioB17mo ago
if you want to throw a better error, yes
Zidan
ZidanOP17mo ago
got it, thanks a lot

Did you find this page helpful?