Is there a way to create a text file (and write some JSON data to it ) using client side code only (no server-side code / web services )?
You can use local storage to store data client-side, but there is no way to do this server-side.
My best guess would be that you need to use javascript localstorage to store json.
example :
var myObject = {};
localstorage['myKey'] = myObject;
var secObject = localstorage['mykey'];
//you couls also use :
localstorage.setItem('myKey', myObject);
secObject = localstorge.getItem('myKey');
I usually "stringify" my JSON before saving it in case i need to modify "myObject" after saving it (because when you copy an object you actually copy a reference to it)
localstorage['myKey'] = JSON.stringify(myObject);
secObject = JSON.parse(localstorage['myKey']);
How are you all missing his point? You are able to generate text files and .csv files on client side and deliver it as a download.
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// Start file download.
download("hello.txt","This is the content of my file :)");
From this link:
https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server
Related
I am working on my own project where I want to create an application, which runs on android and iOS. I decide using HTML, CSS and JavaScript for creating a PWA. The app should enable the user to manage recips for tart incl. Cost calculation. My problem is, that I want to save the recips/ingredients in form of a table. The data should be stored permanently locally on the device. With the method "localstorage" the data are only saved temporarily. I don't want to host a webserver/database. The data should not be lost when the user delete the local cache of the browser.
Is it possible to store general data with java script, for example in a text file, outside of the browser's cache?
In your case indexedDB would be my go to solution. It can be deleted by a user as all data stored in the browser. Browser can't store data in text files (at least as per October 2021)
It is possible. but it's not straightforward it must be done manually by the user.
You can generate your DB as a downloadable file -eg. .txt or .csv- and provide the download link for the user or just auto-download it.
here's an example.
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// Start file download.
document.getElementById("dwn-btn").addEventListener("click", function(){
// Start the download of yournewfile.txt file with the content from the text area
var text = document.getElementById("text-val").value;
var filename = "yournewfile.txt";
download(filename, text);
}, false);
to load the data you can create an import button that receives the data and populates the table.
here's how you can read file data
function readImage(file) {
// Check if the file is text.
if (file.type && !file.type.startsWith('text/')) {
console.log('File is not an textfile.', file.type, file);
return;
}
const reader = new FileReader();
reader.addEventListener('load', (event) => {
img.src = event.target.result;
});
reader.readAsDataURL(file);
}
I recommend using this approach with indexedDb or local storage.
I want to make a level editor for my platformer game with phaser and I am saving the data in json files. I want to write json with javascript and I searched then i came to know that we can write it first writing this const fs = require("fs") and many more but on this line I get error require is not defined. I want to create a json file. I using it in the browser with windows 7. how can I use require to do so.
If there is any other way to write json file with js, then please tell.
require doesn't exist on the browser/client side. Also, you cannot use fs as well, it should be implemented on the back-end side. Please use the following approach -
function download(filename, json) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + JSON.stringify(json));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
I want to download a file (client only) which contains a stringified JSON object. For months everything went well until I needed to stringify a big json object.
The text file is always created but the JSON object is simply cut off(if I change the json object it is cut off in different places).
I checked and the whole JSON object is correctly stringified and put into the href attribute but it is not totally present in the downloaded text file.
const file = document.createElement('a');
file.setAttribute('href', 'data:text/plain;charset=utf-8,' + JSON.stringify(jsonObj));
file.setAttribute('id', 'tcDownload');
file.setAttribute('download', fileName);
file.style.display = 'none';
document.body.appendChild(file);
file.click();
document.body.removeChild(file);
So I am wondering if where is some sort of size restriction while using client based downloading.
Works fine now thank you: epascarello
SOLUTION:
const str = JSON.stringify(tc);
var blob = new Blob(str.split(''), {type: 'text/plain'});
const file = document.createElement('a');
file.download = 'myFile.txt';
file.href = URL.createObjectURL(blob);
document.body.appendChild(file);
file.click();
I have a javascript object that contains some information.
I want to convert this into JSON and download it as a .json file.
Seems like I can just to JSON.stringify(obj) to convert it into JSON
but how do I actually download it as a .json file?
I'm not sure this is a React-specific issue if you're just looking to download data via JavaScript, but here's a snippet I use that creates a link to download the data content, virtually clicking the element, and finally removing it from the DOM. It should support both modern browsers and older IEs:
private exportToJson(objectData: SomeObject) {
let filename = "export.json";
let contentType = "application/json;charset=utf-8;";
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([decodeURIComponent(encodeURI(JSON.stringify(objectData)))], { type: contentType });
navigator.msSaveOrOpenBlob(blob, filename);
} else {
var a = document.createElement('a');
a.download = filename;
a.href = 'data:' + contentType + ',' + encodeURIComponent(JSON.stringify(objectData));
a.target = '_blank';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
}
It's also worth noting that there are a number of ways to approach this as cited in this SO question.
For those arriving here and searching for an easier solution:
<a
href={`data:text/json;charset=utf-8,${encodeURIComponent(
JSON.stringify(YOURJSON)
)}`}
download="filename.json"
>
{`Download Json`}
</a>
You won't be able to create a file directly on your computer's file system as this would be a huge security risk. You cannot do this from a web page using JavaScript.
You could write a server side service to post your state to and it creates a file - you may then download the file or be content with where your server side stores it.
Another way via inMemory Create a file in memory for user to download, not through server
I'm currently using GM_setValue and GM_getValue to store data in a userscript I made in Greasemonkey. I'd like to be able to easily save the data in the sqlite database GM is storing all of the data in, from within the script itself.
For exmaple, create a link that says "Backup data" in the upper right corner of the page. When clicked, it would download either the .sqlite file directly, or the JSON.stringify()'d value of it.
Is this something that's possible? I tried to adopt the code from here: Create text file in JavaScript but it's ugly as sin, a massive hack job, and requires the use of unsafeWindow.open() which I can't imagine will scale well when/if I end up having a JSON string 100k characters long
u can create a downloadable file in this way
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
you can call this function
download('filename.sqlite', 'your-db');