Unfortunately, as of September 2018, there is no cross-browser solution available for client-side file writing.
For instance: While in browsers like Chrome we currently have the ability to write files using FileSystemFileEntry.createWriter() through a client-side call, it is noted in the documentation that:
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.
For IE (excluding MS Edge), ActiveX could be used, but this is limited to specific clients.
If you wish to update your JSON file across different browsers, you will need to utilize both server and client-side approaches.
The client-side script
On the client side, you can send a request to the server and then process the response from the server. Alternatively, you could also read a file using FileReader. Cross-browser file writing requires a server component (refer to the server section below).
var xhr = new XMLHttpRequest(),
jsonArr,
method = "GET",
jsonRequestURL = "SOME_PATH/jsonFile/";
xhr.open(method, jsonRequestURL, true);
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
// Convert JSON into JavaScript object
jsonArr = JSON.parse(xhr.responseText);
// Add a new value:
jsonArr.push({"nissan": "sentra", "color": "green"});
// Send the updated JSON file to the server with a new request:
xhr.open("POST", jsonRequestURL, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// Handle POST response if needed
xhr.send("jsonTxt="+JSON.stringify(jsonArr));
// Server handling required to write updated JSON to the file
}
};
xhr.send(null);
Server-side scripts
Various servers can be utilized, but PHP and Node.js servers are specifically discussed here.
You can search for "free PHP Web Hosting*" or "free Node.js Web Hosting". For PHP server, consider 000webhost.com, and for Node.js, check out this list.
PHP server-side script solution:
The PHP script for reading and writing from a JSON file:
<?php
// This PHP script must be located in "SOME_PATH/jsonFile/index.php"
$file = 'jsonFile.txt';
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
file_put_contents($file, $_POST["jsonTxt"]);
}
else if($_SERVER['REQUEST_METHOD'] === 'GET')
{
echo file_get_contents($file);
}
?>
Node.js server-side script solution:
Note that Node.js involves a different approach compared to normal browser JavaScript. It's recommended to study introductory books before delving into Node.js development:
- Learning Node: Moving to the Server-Side
- Node.js Web Development: Server-side development
The Node.js script for reading and writing from a JSON file:
var http = require("http"),
fs = require("fs"),
port = 8080,
pathToJSONFile = '/SOME_PATH/jsonFile.txt';
http.createServer(function(request, response)
{
if(request.method == 'GET')
{
response.writeHead(200, {"Content-Type": "application/json"});
response.write(fs.readFile(pathToJSONFile, 'utf8'));
response.end();
}
else if(request.method == 'POST')
{
var body = [];
request.on('data', function(chunk)
{
body.push(chunk);
});
request.on('end', function()
{
body = Buffer.concat(body).toString();
var myJSONdata = body.split("=")[1];
fs.writeFileSync(pathToJSONFile, myJSONdata); //default: 'utf8'
});
}
}).listen(port);
Related links for Node.js: