Skip to content

Instantly share code, notes, and snippets.

@cecilemuller cecilemuller/mjpeg.js
Last active Jul 8, 2019

Embed
What would you like to do?
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 = http.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
You can’t perform that action at this time.