Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return image using API – Pure NodeJS (no Express)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}/`);
});

>Solution :

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 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading