Last active
July 11, 2020 01:34
-
-
Save davidmurdoch/dc37781b0200a2892577363f30b6c545 to your computer and use it in GitHub Desktop.
C#'s using in JS, ish
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
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