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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With