HTML 5 local storage - html

Can I save data to to either CSV or XML files on offline on client-side via HTML5?

The offline storage is an internal storage. It is not meant to export some files to a specific format / specific folder on disk.

The web storage API stores data as [key,value] pair where both key,value are Strings.
So data in any format needs to adhere to this mechanism for local storage. So for example, if you have a JSON object like :
{
name:'John',
gender:'male'
}
You can store it (through JavaScript) after passing it as a string like :
localStorage.setItem("myObj","{name:'John',gender:'male'}");
For JSON objects, use JSON.stringify() to convert them to strings and use JSON.parse() to read them back.

You can use localstorage, but that only allows you to store something on browsers' internal storage (you cannot decide where and how to write data).
There's also a File API, but is at its very early stages and, by now, it doesn't allow to store files arbitrarily on the client:
HTML 5 File API

Let say you have created array or object like this.
var arrayOrObject = [{obj1:{name:John, age:16}},{obj2:{name:Jane, age:17}}];
you can save this data to local devices by using localStorage.
if (typeof(localStorage) == 'undefined' ) {
alert('Your browser does not support HTML5 localStorage. Try upgrading.');
}
else {
try {
localStorage.setItem("storedArrayOrObject", JSON.stringify(arrayOrObject));
//saves to the database, “key”, “value”
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert('Quota exceeded!'); //data wasn’t successfully saved due to quota exceed so throw an error
}
}
}
To get the data in Array or Object Structure:
var getStoredArrayOrObject = JSON.parse(localStorage.getItem('storedArrayOrObject'));`
To remove the localStorage Data:
localStorage.removeItem('storedArrayOrObject');
Don't recommend this but available:
localStorage.clear();

You could save and export as csv like this... http://joshualay.net/examples/StamPad/StamPad.html

Related

Local persistent storage

I have a meteor react app and I need a way to save some info locally which will also be persistent. For example, if a user save a json, I want to use that same json even if the app is closed and reopen later. I tried groundDb but it requires server side as well. I need this feature to enable each user to save info such as game level. It will be great if I can use it on the web as well and not just for native versions. Thanks!
To join the pedants, here's the proper explanation:
You should first convert your object literal into JSON using the global JSON object and its stringify method:
let data = {a: 'some', b: 'data', c: null};
let json = JSON.stringify(data);
localStorage.setItem('data', json);
When you want to retrieve the data and use it in your application, you'll need to parse the JSON back into an object literal:
let json = localStorage.getItem('data');
let data = JSON.parse(json);
localForage
One option, which we use, is the npm package localforage which provides an asynchronous storage wrapper for localStorage and allows you to save data of any type. You can configure your store, and create multiple instances of local storage.
You can store any type in localForage; you aren't limited to strings like in localStorage.
Setting up localforage is similar to using localStorage except you have to use asynchronous calls:
Using Promises (Note you can use callbacks if you are not using the ES6 API)
Store your data
localforage
.setItem(
'state', data
)
.catch(console.error.bind(console))
Retrieve your data
localforage.getItem('state')
.then(data => /* ... */ )
.catch(console.error.bind(console))
Name your store
localforage.config({
name: 'myStore'
})
You can read more about localForage here.
yup it is quite easy. take the object you want and stringify it and then store in the local storage. JSON objects are string objects and not string per say. so when you store it to local storage it can not be stored as the object but the need to convert it to a json string.
to add : localStorage.setItem();
to retrieve : localStorage.getItem();
another good practice can be to, retrieve the data on log in, store it in an array and then store back into localstorage. so you wont have any junk data and its always up to date.
to clear : localStorage.clear(); Note: this will clear the entire localstorage.
also note that there is a size limit on the localstorage. most browsers allow 5-10 mb.
if you have large amounts of data you can also indexedDB. its fairly new but better for large amounts of data to be stored in the browser. for now i think only IE has a good implementation.
Use standard localStorage: https://developer.mozilla.org/en/docs/Web/API/Window/localStorage
localStorage.setItem('xyz', JSON.stringify(object));
const object = JSON.parse(localStorage.getItem('xyz'));
It should be easy. Stringify the Object to make it a string then you save it. Follow this:
var dataToStore = JSON.stringify(data);
localStorage.setItem('someData', dataToStore);
You serialize the JSON when saving to localStorage:
var serializedData = JSON.stringify(data);
localStorage.setItem('dataKey', serializedData);
And deserialize it when retrieving from localStorage:
var serializedData = localStorage.getItem('dataKey');
var data = JSON.parse(serializedData);

HTML5 localstorage: store and download file

How can I use HTML5 local storage to save a little exe file and then download it by clicking the button?
Localstorage as you think is not a DataBase or even the File System, it's just some plain JSON files that store tiny bits of data in key: value pairs.
If you have worked with JSON before this will be very easy to grasp the Idea behind it.
Below is an example of setting and retrieving values from Local-storage:
locastorage.setItem('KEY',JSON.stringify('VALUE'));
// KEY is kind of like the variable name and the VALUE is the actual Data
JSON.parse(locastorage.getItem('KEY'));
// You use the KEY to access the value
// Using JSON methods stringify and parse just to be on the safer side.
HTML5 Localstorage is not for files.
Have a look at Mozilla's documentation here: https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
Instead it's for key/value pairs.
// Save data to the current local store
localStorage.setItem("username", "John");
// Access some stored data
alert( "username = " + localStorage.getItem("username"));
To start a download, you may want to look at a question like Download File Using Javascript/jQuery

Data array from Couchdb documents into D3

I am having a problem integrating Couchdb and D3. D3 is a Javascript library that performs document driven data visualization. Couchdb is a document database. They were made for each other.
D3 binds an array of data to DOM elements of a web page. In most of the examples I have seen on the web or in books, people are working on a static data set. Generally, examples will show an array written into the Javascript or a text.csv file loaded into the page.
I would like to take data directly from database documents and load it into D3. I'm uncertain how to do it. I have seen one example on the web where a person has loaded all of their data as an array into one couchdb document and then brought the data into index.html with a couchdb.jquery call:
/ This function replaces the d3.csv function.
$.couch.db("d3apps3").openDoc("sp500", {
success : function (doc) {
var data = doc.data;
data.forEach(function(d) {
d.date = formatDate.parse(d.date);
d.price = +d.price;
})
I tried something similar with db.allDocs:
<script type="text/javascript">
$dbname = "dataset2";
$appname = "dataset2";
$db = $.couch.db("dataset2");
$db.allDocs({
success: function (data) {
console.log(data)
}
});
</script>
I could get the data to render in console.log, but could not get it into D3 and index.html. I also realized that the datastream resulting from db.allDocs is limited to the _id and _rev of each document.
I also tried to GET the data from a Couchdb view with a d3.json call. That wouldn't work because d3.json is looking for an existing .json file.
It's funny, I can call the view with cURL using a GET command and see the datastream, but can't seem to bind it with D3.
~$ curl -X GET http://anywhere.com:5984/dataset2/_desing/list_view/_view/arnold
{"total_rows":25,"offset":0,"rows":[
{"id":"dataset.csv1","key":"0","value":null},
{"id":"dataset.csv2","key":"1","value":null},
{"id":"dataset.csv11","key":"10","value":null},
{"id":"dataset.csv12","key":"11","value":null},
Any ideas would be appreciated.
Part four of https://gist.github.com/anonymous/9275891 has an example that I think you'd appreciate. You don't need to rely on the jquery.couchdb library at all - d3 knows enough abuot http and json to work right out the box. The relevant piece of code is:
d3.json("_view/pricetimeseries", function(viewdata) {
// We just want rows from the view in the visualisation
data = viewdata["rows"];
data.forEach(function(d) {
// the key holds the date, in seconds
d.date = new Date(d.key);
d.price = +d.value;
});
// rest of the visalisation code
HTH
If the page in which your D3 code is embedded is not served from the same domain (+ port) than CouchDB you will have to enable Cross-Origin Resource Sharing.
Assume your page is at http://example.com/data.html which contains JavaScript D3 code that acesses data from http://db.example.com/ or http://example.com:5984/. In that case your browser (which is executing the JavaScript) will by default deny such (cross-origin) requests unless the requested domain explicitly allows it.
There are basically two solutions to this:
Serve both the data and the page from the same domain, either by
putting a reverse proxy in between that maps resources to upstream servers (eg /couch to your CouchDB server and everything else to your web server)
serving your static files directly from CouchDB
or by allowing Cross-Origin Resource Sharing, which is available in CouchDB since version 1.3. You can find a list of relevant settings in the CouchDB docs on CORS.

Download Client Side Json as CSV

I am using the angularJS frontend framework and nodejs/express as a backend server to send and receive JSON. The backend sent a large JSON object to the frontend and I was wondering if I could download the JSON object from the frontend in CSV format.
The data is stored as json in an scope variable: $scope.data in an angular controller. Then I converted the data to a string in CSV format in the variable $scope.CSVdata. How do I get the CSVdata to download from the client browser?
I know nodejs can be set up to send a file in CSV format but it would be nice to keep the backend a clean JSON api.
Referencing this post I've thrown together quick demonstration on how this may be done using AngularJS:
JavaScript Demo (Plunker)
I've wrapped the referenced Base64 code in a service, and use it in the following way:
$scope.downloadCSV = function() {
var data = Base64.encode($scope.CSVData);
window.location.href = "data:text/csv;base64," + data;
};
There are some disadvantages to this method however as mentioned in the comments. I've pulled out some bullet points from the Wikipedia page on this subject. Head over there for the full list.
Data URIs are not separately cached from their containing documents (e.g. CSS or HTML files), therefore the encoded data is downloaded
every time the containing documents are re-downloaded.
Internet Explorer 8 limits data URIs to a maximum length of 32 KB. (Internet Explorer 9 does not have this limitation)
In IE 8 and 9, data URIs can only be used for images, but not for navigation or JavaScript generated file downloads.[7]
Base64-encoded data URIs are 1/3 times larger in size than their binary equivalent. (However, this overhead is reduced to 2–3% if the
HTTP server compresses the response using gzip)
Data URIs do not carry a filename as a normal linked file would. When saving, a default filename for the specified MIME type is
generally used.
[ . . . ]

Sencha-touch localization. Use a store or a global JSON object?

I'm writting an application in Sencha-Touch 1.1 and I want to add localization to strings.
I've thought (but not implemented) of two ways.
Create seperate JSON files for each language (en-US.json, el-GR.json
etc) and use a proxy and a store to load the data, changing each
time the proxy url (json file destination). The problem is that I don't know how to extract the data from the store afterwards.
Create a global JSON object which then I inflate (parse the json file
and turn it into an object). The problem here is that I cannot seem to find a way to parse a JSON file without using a reader/proxy combo.
Is there any optimal solution for localizing strings in sencha-touch?
A common approach is to extract all of your strings into class level properties and have separate locale files which override these classes and their string properties.
For example, if I had a panel like this:
MyApp.MyPanel = Ext.extend(Ext.Panel, {
myPanelContent: 'This is your text to be translated...',
initComponent: function(){
Ext.apply(this, {
html: this.myPanelContent
});
MyApp.MyPanel.superclass.initComponent.call(this)
}
});
And then you would have a locale file along the lines of:
Ext.override(MyApp.MyPanel, {
myPanelContent: 'This is a translation of my text to another language'
});
You can then either load the correct locale file when your app is loaded (after the views themselves have been loaded) or dynamically load the locale files during runtime (this would require logic to update each of the views with the current value).
Hope this makes sense, give me a shout if it doesn't!
Stuart