4

I'm new to Nuxt JS. And am trying to figure out how to download a JSON file from a remote URL source to use locally as part of the nuxt build process?

So, for example, if the JSON file is at:

https://path/to/my/json

Then in my nuxt app, I DON'T want to connect to that JSON file remotely, but rather use it locally. So, when I publish my site, I don't want it to be dependent on the external resource.

At the moment, I'm accomplishing this with gulp, using the gulp-download-files plugin.

kissu
  • 40,416
  • 14
  • 65
  • 133
user791793
  • 413
  • 1
  • 6
  • 19
  • Can you download the file and put it locally in your project? – kissu May 25 '21 at 12:06
  • Yes, but I don't want to do this manually. Especially as this means each time the JSON file changes, I'd have to remember to download the file manually again. Automating this step into the build process appears to be the more sensible solution – user791793 May 25 '21 at 13:12
  • But, you told us that you don't want to download it right? I mean, what's the difference between using a remote file and downloading it to use it locally? If it is not available at the time of build, you won't be able to have it locally neither. You can't download it (`axios`) or you don't know how to write a JSON down locally (`node's fs`)? Because you could totally inject the JSON itself into your build step by fetching the file (at build time). – kissu May 25 '21 at 13:19
  • Re: "Because you could totally inject the JSON itself into your build step by fetching the file (at build time)": That's what I'm trying to do. I don't know how/where to write the node js to fetch the JSON. Does that make sense? – user791793 May 25 '21 at 13:29

1 Answers1

5

You can start by installing axios (you can still have @nuxtjs/axios alongside your project):
yarn add -D axios

Then, let's take JSON placeholder's API for testing purposes, we will try to get the content located here: https://jsonplaceholder.typicode.com/todos/1
And save it to a local .json file in our Nuxt project.

For that, head towards nuxt.config.js and write your script there

import fs from 'fs'
import axios from 'axios'

axios('https://jsonplaceholder.typicode.com/todos/1').then((response) => {
  fs.writeFile('todos_1.json', JSON.stringify(response.data, null, 2), 'utf-8', (err) => {
    if (err) return console.log('An error happened', err)
    console.log('File fetched from {JSON} Placeholder and written locally!')
  })
})

export default {
  target: 'static',
  ssr: false,
  // your usual nuxt.config.js file...
}

This will give you a nice JSON file that you can afterwards import back into your nuxt.config.js and work on!

enter image description here

kissu
  • 40,416
  • 14
  • 65
  • 133