Last active
April 4, 2023 13:56
-
-
Save mandaputtra/ebec973fba02b038f8d0c78b2f0d1530 to your computer and use it in GitHub Desktop.
Stream video using node.js
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
"use strict"; | |
// Require the framework and instantiate it | |
import fastify from "fastify"; | |
import fs from "node:fs"; | |
import { join } from "node:path"; | |
import { Readable } from "node:stream"; | |
const app = fastify({ logger: true }); | |
async function* streamFile() { | |
const stream = fs.createReadStream(join(__dirname, "..", "video-movie.mp4")); | |
for await (const chunk of stream) { | |
yield chunk; | |
} | |
} | |
// Declare a route | |
app.get("/", async (_, reply) => { | |
reply.type("video/mp4"); | |
return reply.send(Readable.from(streamFile())); | |
}); | |
// Run the server! | |
const start = async () => { | |
try { | |
await app.listen({ port: 3000 }); | |
} catch (err) { | |
app.log.error(err); | |
process.exit(1); | |
} | |
}; | |
start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment