0

I have an img tag in my html that requests the image from nodejs server. In my server js file I have below code to send image response but I observed data is not rendered on client side. Any suggestions?

const getFile = (filePath) => {
    return new Promise((resolve, reject) => {
        fs.readFile(filePath, (error, data) => {
            if (!error) {
                resolve(data);
            } // enter code here
            else reject(error);
        });
    });
};

getFile(test.jpg).then((data) => {
    response.statusCode = "200";
    response.setHeader("Content-Type", "image/jpg");
    response.end(data, "base64"); // Also tried response.end(data, "binary")
})
.catch(error => console.log(error));

2 Answers2

0

Is this an Express application? If so, your best bet is to use the static middleware. Put all your static (binary) files in one folder, expose it with the static middleware, and load it that way.

Michael Pratt
  • 3,438
  • 1
  • 17
  • 31
0

Instead of fs.readFile, using fs.createReadStream and piping the chunks worked for images.

let frstream = fs.createReadStream(url);
        response.statusCode = "200";
        response.setHeader("Content-Type", "image/jpeg");
        frstream.pipe(response);