Best way to store data to be read by JS - javascript

I am new to Javascript and HTML5.
What is the best way to store text data to be read in JS.
I want to load all the characters of a file into an array, the file is similar to a map file and is stored amongst my resource file.
In Java I would create a text file and read each byte into an array, what is the equivalency of doing that in JS? Does JS have a better method of doing this?

Best way - create .js file with JSON encoded data. Almost all languages have functions for this, json_encode in PHP for example.
You can create a file like:
window.data = {something: true, fromfile: ['f','d','s']};
and include it as javascript file on html page:
<script src="data.js"></script>
So you'll have that array in window.data.
Or create a file:
{something: true, fromfile: ['f','d','s']}
And load it with jQuery's AJAX:
$.post('fileURL',{}, function(data) { console.log(data); }, 'json');
and get it at any moment you need it. You can also generate such data at any time with server-side scripts to get actual data, just change fileURL.js to server-side script's URL.
You can also change last parameter (json) to 'text' and get file content as string. But I'd not trust it for binary files, better to convert it on server side to JSON.

Related

Reading local BSON file in Javascript

I have an HTML 5 game. I'm using webpack/typescript for development.
There is some data I have which I was including by using require like the following
const dataJson = require('scripts/data/data.json');
I would like to do the equivalent, except with bson. I tried the naive approach of doing something like this
const dataJson = require('scripts/data/data.bson');
but this of course fails since there is no loader (won't compile with currently no loaders are configured to process this file.).
I'd like to then include the file locally, load the file and then deserialize the bson. Or I'd like to embed the bson like when using require. This is some tool generated data, so it will be in a data file.
I haven't been able to figure it out. I've tried the following. But this results in the result containing either the bits of File or what looks like the content type (if done as readAsDataURL).
What I have tried
const file = new File(['data'], 'assets/data.bson', { type: 'application/bson' });
const reader = new FileReader();
reader.onload=(theFile) => {
if (theFile.target) {
console.log(theFile.target.result);
}
} ;
reader.readAsDataURL(file);
//reader.readAsBinaryString(file);
What is the correct method to load a local binary file? Presumably, once I have the data, I can just call deserialize from the bson package.
Okay, I'm adding some corrections here.
My method to read the files is wrong. I know understand File will actually create a file. So when this is passed to FileReader it gets the value of the both bits passed in.
I have since discovered I can get the local files 2 ways. I can use XMLHttpRequest as well as the raw-loader loader.
However once I do this. I cannot seem to convert the contents into JSON using bson. Any variant of deserialize, serialize, parse, or stringify has some issue.
Does anyone happen to have the correct method to convert the BSON contents into either a Javascript Object?
Note that the BSON is generated from python using pymongo. My code to generate the BSON is the following.
with open(args.output_bson, 'wb') as fp:
encoded = bson.encode(data_meta.to_dict())
fp.write(encoded)
to_dict is a dictionary. I output both the JSON (using json) and BSON.
I also tested the file with bsondump and it does indeed convert to JSON. So it does appear the file I've loaded is valid.
you can use bson
then call:
BSON.deserialize(theFile.target.result);

Displaying a generated JSON file on a simple website

I have a Java tool, which schedules a task every 24 hours and writes the result in a result.json file. Now I want to display this result.json file on a simple website, but I know that it's not natively possible with JavaScript to access local files. But what other, simple ways exist for this problem? I try to avoid a webservice to keep the scheduling-program and the website on the same server.
Thanks!
You can use the object FileReader for read the file stream from your system and gets the JSON file in a string, later use JSON.parse() to get the JSON in JS object and iterate over it for pretty representing in document DOM, or you can print the string in the HTML without parse to JS object.
Here there are a very completely example of FileReader.

Change JSON File with JavaScript

Does changing a JSON file with JS acutally affect the JSON file or does it only change the JSON file in temp memory?
Code
user.properties[0].firstName = "Jane";
This is from Replacing a property value in JSON.
Edit
I am not using a server to develop my website, but will be using one when I post it.
That would only affect the json in memory, you would then need to write the changes back to the filesystem for it to update the file contents.

access a certain line from a file and change it using javascript

I have a XML File and I need to access that file in Javascript.
I need to get a certain line and change it.Here is an example:
changeFileCode("data.xml", 12, "New Data");
// The first paramater is for the file we want.
// The second paramater is the line we want.
// The third paramater is the new content we want written
Is there a way to do it?
P.S.: I don't want a piece of code that has 1000 lines.
You should not rely on Line/Columns numbers in XML. because XML neglect white-spaces.
But you can target a specific node and change its value using JQuery.
Let's say you want to do that from a client-side, because that's what javascript do, you will have to get that XML file from the server, in purpose to edit the particular parts then send it back to the server to save it; for example:
$.get("yourGetUrl.php", function(data) {
var xml = $(data);
xml.find("yourNode").text("yourNewData");
$.post("yourPostUrl.php", xml, function(resp) {
alert(resp);
}, "xml");
});
Javascript cannot directly access the local file system. The safe way to do this would be to get the user to provide the file via an
<input type="file"/>
element.
You can then manipulate the file using the File Api
The user will then need to re-save the altered file.
The other way to achieve this would be to write a server side api using whatever technology you fancy (php/asp etc) to manipulate files based on parameters and then call it using ajax from your web page.

Need help about accessing a JSON file using JavaScript without the use of any servers

I'm just beginning with JavaScript and I was wondering if I can access a JSON file on the localhost without the use of any servers (like WAMP). I was planning to just read the contents of a JSON file and reflect its contents to an HTML file.
Short answer, yes you can.
Make an XMLHttpRequest against a static file such as: resources/myJSON.json (the extension is merely for organization, you can call the file whatever you want really).
Parse the response as JSON.
Obviously the file must contain a properly formatted JSON object of data, but as long as that's the case, you can load static JSON from a file to "simulate" remote connectivity to a server.
When you're browsing a file as: file:// on your system, it should treat the relative paths correctly.

Categories

Resources