Skip to content

Instantly share code, notes, and snippets.

@yalamber
Forked from cecilemuller/mjpeg.js
Created April 14, 2020 09:30
Show Gist options
  • Save yalamber/7031c6d0cf004260078fb8002cc50060 to your computer and use it in GitHub Desktop.
Save yalamber/7031c6d0cf004260078fb8002cc50060 to your computer and use it in GitHub Desktop.
Emit a looped serie of images as an MJPEG stream using Node.js
'use strict';
const {readFileSync} = require('fs');
const {createServer} = require('http');
const {EventEmitter} = require('events');
let bufferIndex = -1;
const buffers = [
readFileSync('1.jpg'),
readFileSync('2.jpg'),
readFileSync('3.jpg'),
readFileSync('4.jpg')
];
const emitter = new EventEmitter();
const server = createServer((req, res) => {
res.writeHead(200, {
'Cache-Control': 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0',
Pragma: 'no-cache',
Connection: 'close',
'Content-Type': 'multipart/x-mixed-replace; boundary=--myboundary'
});
const writeFrame = () => {
const buffer = buffers[bufferIndex];
res.write(`--myboundary\nContent-Type: image/jpg\nContent-length: ${buffer.length}\n\n`);
res.write(buffer);
};
writeFrame();
emitter.addListener('frame', writeFrame);
res.addListener('close', () => {
emitter.removeListener('frame', writeFrame);
});
});
server.listen(8000);
setInterval(() => {
bufferIndex++;
if (bufferIndex >= buffers.length){
bufferIndex = 0;
}
emitter.emit('frame');
}, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment