Fetch local json file for autocomplete provider


#1

I’m following a tutorial from codersblock.com on “creating an autocomplete for atom”, and wanted to read a local json file containing keywords. The file is being hosted in the same computer using a web server, I can load the file using a web browser like this:

http://localhost:8080/json/keywords.json

But my plugin refuses to load it through javascript using the fetch() method. It works fine if I pass a normal url like this one:

https://cdn.rawgit.com/lonekorean/atom-autocomplete-boilerplate/55500674/data/advanced.json

But again, fails to read any local file. Is it even possible to load a local file?


#2

You can read suggestions from anywhere, as long as your package’s getSuggestions function returns an appropriately formatted array.

Mind sharing the tutorial and your code with us?


#3

Yes of course, the tutorial can be found here:

And more specifically, this is the code that Im using:

I just changed the API_URL constant to my local url which looks like this:

http://localhost:8080/json/keywords.json

The local json file is well formatted because is exactly the same as the one used in the tutorial, this one:

Thanks!


#4

Okay, instead of all that fetch() stuff, just have getSuggestions look up the contents of your .json file and then parse it. It should look something like this:

const fs = require('fs')

...

  function getSuggestions(options) {
    return new Promise( (resolve) =>
      fs.readFile('intermediate.json', (err, data) => {
        if (err) throw err
        resolve(JSON.parse(data))
      })
    )
  }

#5

Thanks, but I should have mentioned that the reason I’m using a web server is because the web server I made manages and updates all these files dynamically, that’s why I wanted to use a localhost url.

If its not possible, then I guess I’m going to adapt my program to something else that works with the example you provided.


#6

I don’t know why fetch() wouldn’t work for the local server.