Skip to content

Instantly share code, notes, and snippets.

@maca134
Created March 17, 2024 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maca134/38d06fdfa1b94e13a24f53f9be5c625c to your computer and use it in GitHub Desktop.
Save maca134/38d06fdfa1b94e13a24f53f9be5c625c to your computer and use it in GitHub Desktop.
Redis Streams for Nodejs
import { Readable, Writable } from "stream";
import { commandOptions, createClient } from "redis";
export const createWriteStream = (client: ReturnType<typeof createClient>, key: string, opts?: { ttlMs?: number }) =>
new Writable({
objectMode: false,
construct: (callback) =>
client
.del(key)
.then(() => callback())
.catch(callback),
write: (chunk, _, callback) =>
client
.append(key, chunk)
.then(() => callback())
.catch(callback),
final: (callback) =>
opts?.ttlMs
? client
.pExpire(key, opts?.ttlMs)
.then(() => callback())
.catch(callback)
: callback(),
});
export const createReadStream = (client: ReturnType<typeof createClient>, key: string) => {
let sent = 0;
return new Readable({
objectMode: false,
async read(size) {
const data = await client.getRange(
commandOptions({ returnBuffers: true }),
key,
sent,
sent + size,
);
if (data.length === 0) {
this.push(null);
return;
}
sent += data.length;
this.push(data);
},
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment