0

For a project, I'm trying to import images from a remote source and copy them in my static folder (I'm not sure which one is better between static or assets) as I generate my routes, so I can use them locally as part of the nuxt build process.

So in my nuxt.config.js file, I'm using the writeFileSync from the Node fs library:

import fs from 'fs'
import path from 'path'

export default {

  // ...

  generate: {
    async routes() {
      const url = `https://via.placeholder.com/300/09f/fff.png`
      const dest = `${path.resolve(
        __dirname
      )}/static/images/fff.png`

      fs.writeFileSync(dest, url, 'ascii') // I also tried 'binary'

    }
  }

I'm getting no error when I run npm run generate but the image is unreadable and weight only a few octets.

davidgourdet
  • 73
  • 1
  • 6
  • 1
    First off, I'd start by only using `async/await` rather than mixing it with `.then` (or only using `.then`). Then, I'll focus on trying to narrow down the issue to a super simple use case. I've achieved to make [something similar](https://stackoverflow.com/a/67689890/8816585) with no issues. So try to fetch an external resource (can be anything), save that one alone (no loop, no fancy logic). I'm not sure to understand all that you're doing here but reducing the reproduction to 3/4 lines as in my example with help us debug the whole thing faster. – kissu Nov 06 '22 at 15:25
  • 1
    Thanks @kissu, you're right, thanks for the link :) I'm gonna update my question to narrow it down. – davidgourdet Nov 06 '22 at 15:33

1 Answers1

0

Reading these responses helped me making it work correctly:

Saving image using fs.writeFile

How to access remote data and write it into a file during Nuxt build?

like this:

async routes() {
  const testUrl = `https://via.placeholder.com/300/09f/fff.png`
  const testDest = `${path.resolve(__dirname)}/static/images/fff.png`

  axios({
    method: 'get',
    url: testUrl,
    responseType: 'stream'
  }).then(function (response) {
    response.data.pipe(fs.createWriteStream(testDest))
  })
}
kissu
  • 40,416
  • 14
  • 65
  • 133
davidgourdet
  • 73
  • 1
  • 6