I am trying to return an image when a user connects to the server ip address, in short, create an API that returns an image.
I had found this solution that worked however now I don't know why it doesn't work.
I don't want to use Express or similar.
UPDATE
Without res.end()
it works, but I don't understand why.
import http from 'http';
import mime from 'mime';
import fs from 'fs';
const hostname = '127.0.0.1';
const port = 8000;
const server = http.createServer((req, res) => {
res.writeHead(200, { 'content-type': mime.getType('./tmp/screenshot.png') });
fs.createReadStream('./tmp/screenshot.png').pipe(res);
res.end();
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
CodePudding user response:
in:
fs.createReadStream('./tmp/screenshot.png').pipe(res);
you already add a pipe
to send data between the server and the client and after finishing sending data, it automatically triggers the end()
event.
if you don't want this behavior. just do this
fs.createReadStream('./tmp/screenshot.png').pipe(res, {end:false});
I hope it's help you :)