I have a data.json file that I would like to load and that I have placed in the lib/ folder. What should I do in order to load that JSON into a variable in the server? Thanks
Use the require() Function to Load JSON Files in JavaScript In JavaScript, we can use the require() method to load files and modules. This takes the path of the local file where it has been saved. With the help of the console. log() function, it loads the data in the server and displays it.
There are three ways you can go about this, it depends what you're most comfortable with & your use case.
The first is to store it as a JS Object
if your json data is { "name":"bob" }
you could use myjson = {"name":"bob"}
in a .js
file in the /lib
folder and just call myjson
when you need it.
Using an http call
You need the Meteor http
package, installed via meteor add http
.
Server Side code
myobject = HTTP.get(Meteor.absoluteUrl("/myfile.json")).data;
Client Side Code
HTTP.get(Meteor.absoluteUrl("/myfile.json"), function(err,result) } console.log(result.data); });
Another way to do it is to fetch the json file ajax style (you would have to put it in your /public
folder though and use Meteor.http
to call it.
Read the file directly
Lastly you could read the file directly, you store your myfile.json
in a private
directory in your project's root:
var myjson = {}; myjson = JSON.parse(Assets.getText("myfile.json"));
If you want to access this on the client side you would have to interface it with a Meteor.methods and Meteor.call
So whichever way you want, the first is the easiest but I'm not too sure how you want to use it or whether you want to pick the file or something
As I am new to all this I suspect this is not the correct way to do this, however this has worked for me...
Three coffee script files, two in the server directory:
server.coffee:
Meteor.startup -> insertSample = (jsondata) -> Fiber(-> Documents.insert name: "Sample doc" data: jsondata ).run() if Documents.find().count() is 0 insertJSONfile("tests/test.json", insertSample)
and insertJSONfile.coffee:
fs = __meteor_bootstrap__.require("fs") insertJSONfile = (file, insert) -> jsondata = undefined fs.readFile file, (err, data) -> throw err if err jsondata = JSON.stringify(JSON.parse(data)) insert(jsondata)
and model.coffee in the root dir:
@Documents = new Meteor.Collection("documents")
On startup this should load and insert the JSON file (in my case I've stored this in the tests directory) into a field in the documents collection.
I would love to hear from others on how this should be done properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With