When converting from promise-based to callback-based APIs, the most obvious way is like this:
promise.then((value) => callback(null, value)).catch(callback);
This has a subtle bug - if the callback throws an error, the catch statement will also catch that error, and the callback will be called twice. The correct way to do it is like this:
promise.then((value) => callback(null, value), callback);
The second parameter of then can also be used to catch errors, but only errors from the existing promise, not the new one created by the callback.
If the Deno equivalent is actually synchronous, there's a similar problem with try/catch statements:
try {
const value = process();
callback(null, value);
} catch (err) {
callback(err);
}
Since the callback is called within the try block, any errors from it will be caught and call the callback again.
The correct way to do it is like this:
let err, value;
try {
value = process();
} catch (e) {
err = e;
}
if (err) {
callback(err); // Make sure arguments.length === 1
} else {
callback(null, value);
}
It's not as clean, but prevents the callback being called twice.
This library has node compatibility
https://deno.land/[email protected]/node
const source = Readable.from(["abc", "def"]);
const hash = createHash("sha1");
const dest = source.pipe(hash);
const result = await new Promise((resolve, _) => {
let buffer = Buffer.from([])
dest.on("data", (data) => {
buffer = Buffer.concat([buffer, data]);
})
dest.on("end", () => {
resolve(buffer)
})
})
Buffer.from([
0x1f,
0x8a,
0xc1,
0xf,
0x23,
0xc5,
0xb5,
0xbc,
0x11,
0x67,
0xbd,
0xa8,
0x4b,
0x83,
0x3e,
0x5c,
0x5,
0x7a,
0x77,
0xd2,
])
for (const algorithm of getHashes()) {
const d = createHash(algorithm).update("abc").digest();
assert(d instanceof Buffer);
assert(d.length > 0);
}
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
const url_ = Deno.args[0];
const res = await fetch(url_);
// TODO(ry) Re-enable streaming in this example.
// Originally we did: await Deno.copy(res.body, Deno.stdout);
// But maybe more JS-y would be: res.pipeTo(Deno.stdout);
const body = new Uint8Array(await res.arrayBuffer());
await Deno.stdout.write(body);