Hey Replit community,
I am currently trying to read and write .json file in my HTML/CSS/JS repl using JavaScript’s fetch() API but I didn’t really succeed at it. I managed to read manually inserted into .json file data, however I still cannot find any way to write the data using JavaScript and not my own hands. Is there such a way? Here is this repl by the way: https://replit.com/@entcode/jsontest?v=1
You cannot write to a file from the front-end, you need to use server-side code. That said, there is sort-of a way of writing to local files now, but I don’t think that would work in this circumstance anyway. You will need to set up a server in order to write to files.
Thanks for your response! As I understand, Node.js repl is a server so from it I can write data into .json files. Suppose I have a Node.js repl with main index.js file, folder “public” with HTML, CSS, JS files (my frontend website) and outside the folder package.json file (with Node setup stuff) and data.json (aka database). As you mentioned, I can only append data to data.json file via index.js (main Node file), however all the data that I need to append (and get it) lie in JS file (temporary storage that empties as soon as I close or reload the tab). Is there a way to somehow transfer data from JS file (supposed path: /public/script.js) to index.js and vice versa? I’ve heard it’s possible to do using fetch API but seems I’m too junior to understand this method
Yep, your absolutely right! fetch
basically sends requests (XMLHttpRequests
I believe, don’t quote me on that though) and your server will need to receive them and act based on these requests.
Here’s an example of what a simple fetch
request looks like:
fetch("/my text file.txt")
.then(function(res /* commonly used name, short for result */) {
return res.text(); // turn the result into text (because the result is actually a whole bunch of information about the server's response)
})
.then(function(text) {
console.log(text);
});
This would probably look somewhat similar to how you’re reading from your text files (I presume you’re either using fetch
or XMLHttpRequest
s, fetch
is the easier and probably better of the two).
To send a request to a server that contains data though is actually a little different. By default, fetch
will send a GET
request, which tells the server we are trying to GET
some information from it. Other commonly used request methods are POST
(send information), PUT
(update information) and DELETE
(delete information). The one we want is POST
(we could probably also use PUT
but it doesn’t really matter; generally GET
is for getting data and POST
is for sending data (and getting a response).
fetch("/", /* this is the options parameter that allows us to customise our request more */ {
method: "POST", // we are sending a POST request
headers: {
"Content-Type": "application/json" // tell the server we are sending text in the JSON format (JSON is probably the most commonly used format for sending data using requests)
},
body: JSON.stringify({
"file": "my text file.txt",
"content": "Hello world!"
}) // body is the actual content we are sending to the server, we need to convert this to a string, but it will be read as on object again by the server
})
.then();
MDN has great documentation of JS, I would recommend reading here if you want more info or better explanations.
Now, I’m going to assume you’re using Express, I’ve only ever used Express…. Setting up an express server is really easy. This is an empty example:
const express = require("express");
const app = express();
app.listen(8080);
That’s actually a functional server, it doesn’t do anything though.
If all of your content is in a folder at this path /public
, I’m guessing you’ve done some research and found this:
app.use(express.static(__dirname + "/public"));
All you need to do is be able to receive POST
requests. Before we receive POST
requests, we want to tell Express to automatically convert data sent via POST
to JSON:
app.use(express.json());
(Pretty simple!)
Next we just need to set up where we will receive POST
requests and how we’ll handle them:
app.post("/", function(req, res) {
console.log(req.body); // this is the JSON data the front-end script sent to us (the server)
// here we want to write to a file using the `fs` package which is built into NodeJS
fs.writeFile(req.body.file, req.body.content);
res.status(200).end(); // send a status of 200 (the request succeeded) before ending the request
});
And hopefully that should be enough to let you do what you’re trying to do!
I’ll try that! Thanks for your help!
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.