Search code examples
javascriptnode.jssveltesveltekit

Downloading images from external source and saving to $lib or static at build time


I have a Sveltekit project set up with adapter-static. I'm pulling in content for my pages from Directus. I'm hosting my images in S3, which is hooked up to my Directus instance so that I can use the Directus filesystem to read these image files from and save to my S3 storage. I am handling audio samples the same way.

At build time, I would like to import / download the remote images and audio samples to my project, the same way I am downloading the text information I need to populate my pages. I am using load functions in +page.server.ts to fetch the data I will need for each page at build time using the Directus API. I am however stumped as to how I can do this for images too. It would be ideal that I can write something in the load function that tells Sveltekit to "fetch all the images and audio samples from this remote folder, then store them in /$lib or in /static so that we can serve local images and audio in the static site" Use case:I'm trying to create an intuitive way for content editors to work on content whilst at the same time trying to decouple the website code from relying on any external provider. If my S3 or Directus instance goes down, the most recent site build should display without problem. This is currently the case for everything except the image and audio assets referenced in my markup. So it would be ideal that my content editor can upload their images to S3 via the Directus instance (which will trigger a site build) and that my project can then download those images and store them locally at build (not on the client side at load time.)

Essentially it should not matter how or where I store my images; the function / package / way to do what I am asking would essentially be the same. Does anybody have advice on where to start / what to look into / npm packages to try to make this happen?


Solution

  • Why not create a separate script that runs before or after vite build?

    {
      "scripts": {
        "build": "vite build && node download-image"
      }
    }
    

    Assuming that you are running the build in a Node.js runtime, the images can be saved into the output directory - /build is the default - using the node:fs module.