How to display locally-generated images


I’m trying to convert a web app that displays local images to an Electron app, and face a hurdle in that the images displayed, while they do come from the filesystem, are first processed by the Sharp Node.js module, and therefore don’t exist on disk. Currently the web client app loads them from a URL at which the server exposes them after being processed by Sharp. I can think of a couple of approaches:

  1. Have Sharp save the created image to a temporary location, and then reference that as a file:// URL. This has the downside that I would need to manage cleanup of the temp folder, and I would also need to take steps to ensure that the renderer doesn’t attempt to load the file from the disk before Sharp has finished creating it.

  2. Have the main process run a sort of internal web server on localhost to provide http:// URLs that the HTML image element can reference, same as in the current web app.

However, neither seems ideal or the obvious choice, and I wondered if there is a better one that I’m not aware of.


I realise this is probably too late to be useful for you, but maybe someone else will find it helpful.

Of the two options you outlined, I would find #2 by far the most preferable. While it does seem a bit clunky, I don’t see anything wrong with the main process spawning a separate process on which to run a simple Node HTTP server to serve images processed from Sharp. Being a child process of the main process would mean it is likely to be run on a different CPU core to both the main and render processes, so image processing will hopefully not impact the general performance of the app. It may even be possible to set up multi-process running for the image server module so that if you’re serving a lot of images at once (e.g. thumbnails processed from originals) you can take advantage of spare CPU cores.

There is a 3rd option: loading the image data dynamically from a NodeJS buffer. Basically convert the contents of the buffer you get from Sharp to a base64-encoded image string as per the SO question and just set that as the src of the image in JS.