Skip to content
python-style with statements for deno
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
testdata
README.md
mod.ts
test.ts

README.md

deno-using

A python-style with statement for deno.

Comes with some Using types, e.g. Open, ChDir, TempDir, and Timeout.

Example:

import * as Deno from "deno";
import { using, Open } from "./mod.ts";

const enc = new TextEncoder();
const dec = new TextDecoder("utf-8");

async function main() {
  await using(new Open('file', 'w'), async (f: Deno.File) => {
  	const data = enc.encode("Hello world!\n");
    await f.write(data);
  })
  await using(new Open('file', 'r'), async (f: Deno.File) => {
  	const data = new Uint8Array(20);
    await f.read(data);
    const text = dec.decode(data);
    console.log(text);
  })
}

main()

Custom types

You can define your own Using types by creating a class which implements Using:

export class Open implements Using<Deno.File> {
  constructor(filename: string, mode?: Deno.OpenMode) {
    this.filename = filename;
    this.mode = mode;
  }
  public async _aenter() {
    this.file = await Deno.open(this.filename, this.mode);
    return this.file;
  }
  public async _aexit(e) {
    this.file.close();
  }
  private file: Deno.File;
  private filename: string;
  private mode: Deno.OpenMode;
}

There is also a corresponding sync version UsingSync.

You can’t perform that action at this time.