Last active
October 19, 2022 15:58
-
-
Save ehaynes99/ff500eccfbb38dd46b5f720f6432bbcf to your computer and use it in GitHub Desktop.
node async Writable or Transform stream
This file contains hidden or 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
/* eslint-disable @typescript-eslint/no-misused-promises */ | |
import { Readable, Transform, Writable } from 'node:stream' | |
import { pipeline } from 'node:stream/promises' | |
export const asyncHandler = (handle: (value: any) => Promise<void>) => { | |
return new Writable({ | |
objectMode: true, | |
write: async (value, _, next) => { | |
try { | |
await handle(value) | |
next() | |
} catch (error) { | |
next(error) | |
} | |
}, | |
}) | |
} | |
export const asyncTransform = (convert: (value: any) => Promise<any>) => { | |
return new Transform({ | |
objectMode: true, | |
transform: async (value, _, callback) => { | |
try { | |
callback(null, await convert(value)) | |
} catch (error) { | |
callback(error) | |
} | |
}, | |
}) | |
} | |
const run = async () => { | |
const readable = Readable.from(['foo', 'bar', 'baz']) | |
try { | |
await pipeline( | |
readable, | |
asyncTransform(async (value) => String(value).toUpperCase()), | |
asyncHandler(async (value) => console.log(value)) | |
) | |
} catch (error) { | |
console.error(error) | |
} | |
} | |
void run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment