Skip to content

Instantly share code, notes, and snippets.

@cecilemuller
Last active December 30, 2022 14:35
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cecilemuller/c8e746a5cb828e83e55892d4742b8a5c to your computer and use it in GitHub Desktop.
Save cecilemuller/c8e746a5cb828e83e55892d4742b8a5c 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);
@benmarten
Copy link

Missing http import at the top ;)
const http = require('http');
Thanks though :)

@ff6347
Copy link

ff6347 commented Aug 27, 2020

@cecilemuller can you give an example for the receiving end in Node.js? I'm trying to draw the images received from a mjpeg stream to a node-canvas and save them again.

@nschikora
Copy link

Thanks a lot for this gist. It goes very well with this node module https://github.com/TypedProject/ts-gphoto2-driver for tethered control (and live previewing) of DSLR cameras.

@DavidVentura
Copy link

it should be boundary=myboundary according to https://stackoverflow.com/a/49416142/3530257

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment