NodeJS app.js requiring a JSON file?
I know that if I had some JSON data in a .js file, that I could, at the end of that .js file, do a module.exports() of that JSON module's name, and then require it in my app.js, and use a res.json() on it. (pics 1-3)
But what if instead of having that JSON data in a js file, it was housed in its own .json file?
I couldn't do a module.exports() from inside a .json file.
Simply requiring the file inside of app.js and using the same res.json() on it doesn't work.
Are we meant with NodeJS to just convert any JSON files to .js first if we intend to use it in app.js, in order to get access to it?
9 Replies
If you want to read a
.json
file you'll need to use the fs
module to read the file, then parse it as a JSON string into a JS object.
As an example (note I'm using ES6 import
syntax instead of CJS require()
syntax):
https://nodejs.org/dist/latest-v18.x/docs/api/fs.html#fspromisesreadfilepath-optionsOkay and then what would I need to do in order to get it to appear on the page when '/' is loaded?
Do I need to send it to a file first?
You can’t send a JS object over the wire. You’ll need to send the JSON file as a string and parse it on the front-end.
Or, even better, let your reverse proxy handle the file system and your app should only handle the business logic. Caddy, nginx, et al are going to be much better at sending files than Node ever will. That’s what they do.
what does sending something "over the wire" mean?
are you saying there's no way to have the express server directly take in a .json file's information, such that it's usable?
JavaScript objects are a construct of the language and can’t be transmitted outside of the local environment. That means you can’t send them from the backend to the front end, that’s why there’s the JSON spec: to serialized a language-specific construct into something that can be sent via HTTP
And no, I’m no saying that. I saying that you can’t send an object via HTTP. What you’re trying to do here is send a file, no use the info. So send the file and let your front end parse and use the JSON
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
That's for serializing and sending a JS object, not for reading a JSON file and sending it
What the OP is asking for is to read and send a file, not a JS object. Interacting with the file system is usually better left to the reverse proxy set up while the API is passed through to the back end.
There's little reason to have the back end read the file and send it when that's what the reverse proxy is desined to do. Best tool for the job and everything
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
You're still not sending a JS object, you're sending a stringified interpretation of it
Since JSON is a string, you can omit the
res.json()
and just res.send()
or whatever Express uses to send string data