Skip to content

Instantly share code, notes, and snippets.

@MariusBongarts
Last active August 2, 2023 06:21
Show Gist options
  • Save MariusBongarts/9f1af54943c42016cccaa1eff8af20bc to your computer and use it in GitHub Desktop.
Save MariusBongarts/9f1af54943c42016cccaa1eff8af20bc to your computer and use it in GitHub Desktop.
Read file with new "using" keyword
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