Skip to content
Advertisement

Using fetch to read and write files

In my code i’ve a file called “orca.txt” it is just a number writen in this. it looks like:

2300

I use fetch to read this number, i get it with:

fetch(‘orca.txt’)

.then(response => response.text())

.then(textString => { contador=textString; });

It works very well, but then after i need to increase the value from the var contador, so I use contador++; after i wanna to save this new value into the file “orca.txt”

i’ve tried this:

contador++;

var ct=contador.toString();

fetch(“orca.txt”,{method:’POST’, body:ct})

.then (response => response.text());

but when i refresh the page or open in server the file orca.txt the value is same.

Can anyone help me how to write a value into a file (server file, no user file) using POST method?

Advertisement

Answer

Using PHP and file_put_contents and JS’s Fetch API with FormData API

enter image description here

Create an index.html file:

JavaScript

create counter.txt file:

JavaScript

Create a saveCounter.php file:

JavaScript

Spin up your localhost server or for a quick test using cli-server run from terminal:

JavaScript

and head to http://localhost:8081 to try it out

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement