Skip to content

Instantly share code, notes, and snippets.

@ehaynes99
Last active October 19, 2022 15:58
Show Gist options
  • Save ehaynes99/ff500eccfbb38dd46b5f720f6432bbcf to your computer and use it in GitHub Desktop.
Save ehaynes99/ff500eccfbb38dd46b5f720f6432bbcf to your computer and use it in GitHub Desktop.
node async Writable or Transform stream
/* 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