Skip to content

Instantly share code, notes, and snippets.

@davidmurdoch
Last active July 11, 2020 01:34
Show Gist options
  • Save davidmurdoch/dc37781b0200a2892577363f30b6c545 to your computer and use it in GitHub Desktop.
Save davidmurdoch/dc37781b0200a2892577363f30b6c545 to your computer and use it in GitHub Desktop.
C#'s using in JS, ish
const fs = require('fs');
const {promisify} = require('util');
const open = promisify(fs.open.bind(fs));
async function using(closable, fn) {
const fd = await closable;
try {
await fn(fd);
} finally {
closable && typeof closable.close === "function" && closable.close();
}
}
using(open("./file.js", "r+"), (fd) => new Promise(resolve => {
const buffer = new Buffer(1024);
fs.read(fd, buffer, 0, 1024, 0, (_, bytesRead, buffer) => {
console.log("bytes read: ", bytesRead);
console.log("bytes: " + buffer.toString());
resolve();
});
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment