Source

lib/s3.ts

import { S3Client } from "@aws-sdk/client-s3";
import Config from "../classes/config";
import { Readable } from "stream";

export const s3 = new S3Client({
    endpoint: Config.s3.endpoint,
    credentials: {
        accessKeyId: Config.s3.accessKeyId!,
        secretAccessKey: Config.s3.secretAccessKey!
    },
    region: "us-east-1" // dummy value
});

/**
 * Converts a stream to a buffer
 * @param {Readable} stream The stream to convert
 * @param {number} [prealloc] The size to preallocate for the buffer
 * @return {Promise<Buffer>}
 */
export async function stream2buffer(stream: Readable, prealloc?: number): Promise<Buffer> {
    return new Promise<Buffer>((resolve, reject) => {
        const _buf = [];
        stream.on("data", (chunk) => {
            if(prealloc && _buf.length + chunk.length >= prealloc) {
                return reject(new Error("prealloc exceeded"));
            }
            _buf.push(chunk);
        });
        stream.on("end", () => resolve(Buffer.concat(_buf, prealloc)));
        stream.on("error", (err) => reject(err));
    });
}