Last active
December 30, 2022 14:35
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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
it should be
boundary=myboundary
according to https://stackoverflow.com/a/49416142/3530257