Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Node FileStream Image to HTML5 FileReader API

How can I use Node FileSystem to open a file but have it sent to and read by the FileReader API?

const myFile = "C:\\Users\\Me\\Image.png";

fs.readFile(myFile, (error, data) => {
    const blob = new Blob(data);

    const fileReader = new FileReader();
    fileReader.readAsDataURL(blob);

    fileReader.addEventListener("load", () => {
        const image = new Image();
        image.src = fileReader.result;

        document.body.appendChild(image);
    });
});

This code doesn't throw an errors, but it doesn't work.

like image 813
Chunky Chunk Avatar asked May 17 '26 06:05

Chunky Chunk


1 Answers

Thanks to the participants in the discussion above, the following code is a working solution. I've purposefully left out error handling for brevity.

const nodeFileSystem = require("fs");

const filePath = "C:\\path\\to\\image\\file.png";

nodeFileSystem.readFile(filePath, (error, data) => {

    const blob = new Blob([data]);

    const fileReader = new FileReader();
    fileReader.readAsDataURL(blob);
    fileReader.addEventListener("load", fileReaderLoadHandler);
});

function fileReaderLoadHandler(event) {

    const fileReader = event.target;
    fileReader.removeEventListener("load", fileReaderLoadHandler);
    
    const image = new Image();
    image.src = fileReader.result;
    image.addEventListener("load", imageLoadHandler);
}

function imageLoadHandler(event) {

    const image = event.target;
    image.removeEventListener("load", imageLoadHandler);

    document.body.appendChild(image);
}
like image 88
Chunky Chunk Avatar answered May 18 '26 20:05

Chunky Chunk