How to get ReadableStream from GridFSBucket?

I need some help how to use the GridFSBucket stream in the streamFile function.
In this working example functions a file on the disc will be read and returned as a stream:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { NextRequest, NextResponse } from "next/server";
import { ReadableOptions } from "stream";
function streamFile(path: string, options?: ReadableOptions): ReadableStream<Uint8Array> {
const downloadStream = fs.createReadStream(path, options); // Replace this
return new ReadableStream({
start(controller) {
downloadStream.on("data", (chunk: Buffer) => controller.enqueue(new Uint8Array(chunk)));
downloadStream.on("end", () => controller.close());
downloadStream.on("error", (error: NodeJS.ErrnoException) => controller.error(error));
},
cancel() {
downloadStream.destroy();
},
});
}
export async function GET(req: NextRequest): Promise<NextResponse> {
const file = req.nextUrl.searchParams.get("file");
const stats: Stats = await fs.promises.stat(file);
const data: ReadableStream<Uint8Array> = streamFile(file);
const res = new NextResponse(data, {
status: 200,
headers: new Headers({
"content-type": "video/mp4",
"content-length": stats.size + "",
}),
});
return res;
}
</code>
<code>import { NextRequest, NextResponse } from "next/server"; import { ReadableOptions } from "stream"; function streamFile(path: string, options?: ReadableOptions): ReadableStream<Uint8Array> { const downloadStream = fs.createReadStream(path, options); // Replace this return new ReadableStream({ start(controller) { downloadStream.on("data", (chunk: Buffer) => controller.enqueue(new Uint8Array(chunk))); downloadStream.on("end", () => controller.close()); downloadStream.on("error", (error: NodeJS.ErrnoException) => controller.error(error)); }, cancel() { downloadStream.destroy(); }, }); } export async function GET(req: NextRequest): Promise<NextResponse> { const file = req.nextUrl.searchParams.get("file"); const stats: Stats = await fs.promises.stat(file); const data: ReadableStream<Uint8Array> = streamFile(file); const res = new NextResponse(data, { status: 200, headers: new Headers({ "content-type": "video/mp4", "content-length": stats.size + "", }), }); return res; } </code>
import { NextRequest, NextResponse } from "next/server";
import { ReadableOptions } from "stream";

function streamFile(path: string, options?: ReadableOptions): ReadableStream<Uint8Array> {
    const downloadStream = fs.createReadStream(path, options); // Replace this

    return new ReadableStream({
        start(controller) {
            downloadStream.on("data", (chunk: Buffer) => controller.enqueue(new Uint8Array(chunk)));
            downloadStream.on("end", () => controller.close());
            downloadStream.on("error", (error: NodeJS.ErrnoException) => controller.error(error));
        },
        cancel() {
            downloadStream.destroy();
        },
    });
}

export async function GET(req: NextRequest): Promise<NextResponse> {
    const file = req.nextUrl.searchParams.get("file");                                
    const stats: Stats = await fs.promises.stat(file);                              
    const data: ReadableStream<Uint8Array> = streamFile(file);                     
    const res = new NextResponse(data, {                                            
        status: 200,                                                                    
        headers: new Headers({                                                          
            "content-type": "video/mp4",                                            
            "content-length": stats.size + "",                                            
        }),
    });

    return res;                           
}

But my data comes from a mongoDB GridFSBucket.
This is how I’m streaming a video file directly from the GridFSBucket:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>export const getServerSideProps: GetServerSideProps = async ({
res,
query: { hash }
}) => {
const database = await mongodb()
const Videos = database.collection('videos')
const { fileId } = await Videos.findOne({ uid: hash })
const Files = new GridFSBucket(database)
const id = new ObjectId(fileId)
const file: GridFSFile = await new Promise((resolve, reject) => {
Files.find({
_id: id
}).toArray((err, files) => {
if (err) reject(err)
resolve(files[0])
})
})
const { contentType } = file || {}
res.writeHead('Content-Type', contentType) // contentType is "video/mp4"
Files.openDownloadStream(id)
.on('data', (chunk) => {
res.write(chunk)
})
.on('end', () => {
res.end()
})
.on('error', (err) => {
throw err
})
return {
props: {}
}
}
</code>
<code>export const getServerSideProps: GetServerSideProps = async ({ res, query: { hash } }) => { const database = await mongodb() const Videos = database.collection('videos') const { fileId } = await Videos.findOne({ uid: hash }) const Files = new GridFSBucket(database) const id = new ObjectId(fileId) const file: GridFSFile = await new Promise((resolve, reject) => { Files.find({ _id: id }).toArray((err, files) => { if (err) reject(err) resolve(files[0]) }) }) const { contentType } = file || {} res.writeHead('Content-Type', contentType) // contentType is "video/mp4" Files.openDownloadStream(id) .on('data', (chunk) => { res.write(chunk) }) .on('end', () => { res.end() }) .on('error', (err) => { throw err }) return { props: {} } } </code>
export const getServerSideProps: GetServerSideProps = async ({
    res,
    query: { hash }
}) => {        
    const database = await mongodb()
    const Videos = database.collection('videos')

    const { fileId } = await Videos.findOne({ uid: hash })

    const Files = new GridFSBucket(database)
    const id = new ObjectId(fileId)

    const file: GridFSFile = await new Promise((resolve, reject) => {
        Files.find({
            _id: id
        }).toArray((err, files) => {
            if (err) reject(err)
            resolve(files[0])
        })
    })
    const { contentType } = file || {}

    res.writeHead('Content-Type', contentType) // contentType is "video/mp4"
    Files.openDownloadStream(id)
    .on('data', (chunk) => {
        res.write(chunk)
    })
    .on('end', () => {
        res.end()
    })
    .on('error', (err) => {
        throw err
    })

    return {
        props: {}
    }
}

So I would think of using the GridFSBucket part instead of createReadStream from the file.
But the res.writeHead and openDownloadStream makes me struggle. How do I get a ReadableStream? Or maybe this isn’t needed?

I need to convert this, because my getServerSideProps is used in an old nextJS application, which uses pages router and I need to migrate to new app router. Therefore I need a server route component.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật