Skip to content

Instantly share code, notes, and snippets.

@mandaputtra
Last active April 4, 2023 13:56
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 mandaputtra/ebec973fba02b038f8d0c78b2f0d1530 to your computer and use it in GitHub Desktop.
Save mandaputtra/ebec973fba02b038f8d0c78b2f0d1530 to your computer and use it in GitHub Desktop.
Stream video using node.js
"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