Node.JS Streams — File

const processUsage = process.memoryUsage();
const totalUsedMemoryInMb = Math.floor(processUsage.rss / (1024 * 1024));
console.log(`Used Memory: ${totalUsedMemoryInMb} MB`);
app.get('/send-sync', (req, res) => {
const filePath = resolve(__dirname, '..', 'upload', 'ex.mp4');
fs.readFile(filePath, (err, data) => {
res.send(data);
});
}
app.get('/stream', (req, res) => {
const { range } = req.headers;
const filePath = resolve(__dirname, '..', 'upload', 'ex.mp4');
const { size: fileSize } = fs.statSync(filePath);
const start = Number(range?.replace(/\D/g, '')) || 0;
const CHUNK_SIZE = 1000000;
const end = Math.min(start + CHUNK_SIZE, fileSize - 1);
const headers = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Type': 'video/mp4',
'Content-Length': CHUNK_SIZE,
};
res.writeHead(206, headers); const fileStreams = fs.createReadStream(filePath, { start, end });
fileStreams.pipe(res);
}
app.get('/send-file', (req, res) => {
const filePath = resolve(__dirname, '..', 'upload', 'ex.mp4');
return res.sendFile(filePath);
}

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Incrementally migrate from SQLite to Room

ES6: Understanding Default & Rest parameters, Spread Operator and its usages

Adding a Responsive Header to React + Ant Design

Currying, kick off.

[Day 6] DOM Events

team@tv-two.com

[Javascript] — Callbacks, Promises, and Async Await (3/3)

Rays Render, extreme fast one-click rendering service has been launched

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Lucas Yuri

Lucas Yuri

More from Medium

Introduction to Node.js

Make your own CLI with Javascript & Node.js!

Example of open index.js file with {Hello World!}.

Using Redis and Node-js to generate Temporary-Invite Codes at Scale.