Last active
August 2, 2023 06:21
-
-
Save MariusBongarts/9f1af54943c42016cccaa1eff8af20bc to your computer and use it in GitHub Desktop.
Read file with new "using" keyword
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from "fs/promises"; | |
const getFileResource = async (path: string) => { | |
const fileResource = await fs.open(path, "r"); | |
return { | |
fileResource, | |
[Symbol.asyncDispose]: async () => { | |
await fileResource?.close(); | |
console.log("Cleanup done"); | |
}, | |
}; | |
}; | |
(async () => { | |
await using fileResource = getFileResource('file.txt'); | |
})(); // File will be automatically be closed when `fileResource` leaves the scope |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment