Javascript write to local file from local file - javascript

I want to create / write to file using javascript from local file. I can read local files using
$.get('file.txt', function (data) {
//my code
}, 'text');
Is there similar way to write to files? It is and will all be done locally, from file to file. Also I can not really use local storage for my purposes.
Edit: I do not want to output blob. And for what I am trying to create - I have this lets call it puzzle that user tries to solve. And I want to log time when he started and when he ended. I do not want them to see their files, becouse they could edit them, same as local storage can be edited or cleaned. I want to create and edit local file without users knowledge. It will all be done locally on my computer.

You can do with this
var data = {"Name":"first name","age":30}
var serializedData = JSON.stringify(data);
var link = document.getElementById('downloadlink');
link.href = makeTextFile(serializedData);
document.getElementById('downloadlink').click();

Related

Write and save file with plain vanilla JavaScript

Is there really no way to save data into a file without nodeJS or without using a download link action of the browser? I want to replace my function that saves data to the localStorage and want to save some user input into a single text file within the project folder.
I have already a file created. How can I write into it and how can I save it?
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
var file = new File(["foo"], dir + "/test.txt", {
type: "text/plain",
});
var str = "My string of text";
Thanks for any idea :)
I think the answer is no. To my understanding the whole point of JavaScript was that it runs within the browser. For security reasons the browser is meant not to have direct code access to the host system, so JavaScript has this limitation by design.
The point of NodeJS was to allow JavaScript code to run on a host computer and expands on the library of functions provided with JS to include things like file manipulation.

How can I get information from a local text file without browsing?

So what I'm trying to do is get text from a file in the same directory as my html file using JavaScript. I want to store an array inside a text file and change it whenever i want instead of constantly having to go into the code, save it, check if it works etc.
I've tried looking around but couldn't find any clear information, most of what I found is using .readAsBinaryString, etc..
I'm mostly seeing things like this but i can't seem find anything which is actually getting information from a textfile without making the person find the text file directory.
function storearray(newval){
var file = "file location;"
var txt = file.txt;
var array = txt.split("|");
txt = txt + newval + " | ";
return array;
}
To read a file from the user's disk you need to use FileReader and the user must explicitly select the file using a file input. (See JavaScript read file without using input).
To read a a file from the website you need to use Ajax (with fetch, XMLHttpRequest or a library that wraps around them like Axios). (See Using fetch from MDN).
If (as it seems here) you want to read data from the website but the website exists only on the user's disk then you still need to use Ajax but will usually run into security restrictions. Some browsers allow you to disable the security protection, but the general solution is to install a web server and load both HTML and the data file using HTTP.
Alternatively, you can store your data in JavaScript (you are generating an array from your text file, you can so that manually or have a build-time script do it) and just load it with a <script> element.

Keeping information about js file in localStorage

I want to create plugin mechanizm. It is, you can load js file on my website and run your js "plugin" (function) when this plugin is set to run (toggled as running).
All this I want to do without any server.
I mean, I want to keep in localstorage js files or path to this files.
It looks to be hard to do because js can't easy access files path.
I handle file by <input type="file"/>
And I react on onchange event. I get event where I can find selected file by event.srcElement.files[0]
With that I can create URL of that object by : URL.createObjectURL(event.srcElement.files[0])
And I tried to store that URL in localstorage but this URL is temporary.
Also I tried to store whole event or just file (event.srcElement.files[0]).
But I need to create string from that if I want to put it to the function .setItem :
localStorage.setItem("functionURL", JSON.stringify(this.functionURL));
.toString() creates [Object Event/File]
JSON.stringify() creates {} from [Object Event/File]
So, maybe is there a way to somehow remember file which we can use as a function without any server ?
So, maybe is there a way to somehow remember file which we can use as a function without any server ?
Basically, no. :-) Web storage only stores strings. You can't use a string to access a file on the user's local filesystem from your web page, for obvious security reasons.
You could, instead:
Make it possible for them to "upload" the file into your page (without a server) by having them identify the file in an input[type=file], reading its text (via the File API), and then storing that text in local storage
On page load, if local storage has code to run, run it
Offer the user a way to delete or update the code they've uploaded to the page
Since all of that happens in the browser, you don't need a server.
Web storage does have size limits, though they're pretty generous, (around 2.5-5MB) and per-origin, so you have that largely to yourself. But if you run into those limits, you could take it further by caching those files via a service worker, but the complexity goes up markedly. I'd start with web storage and only move on if you really need to support massive files.
#1 (reading the script file the user identifies via an input[type=file]) is really simple on modern browsers:
var file = input.files[0];
var fr = new FileReader();
fr.onload = function() {
// Use `fr.result` here, it's a string containing the text
};
fr.readAsText(file);

Read/Write to JSON file in root directory of simply markup project

I have a very simple project. It's only local and I don't require it to ever be online. I'm perfectly content running it by opening index.html in chrome. Along with my html, css, and javascript file there is a data.JSON in my root directory of my project. My question is: can I read and write to this file? Or is there a possible alternative to simple data persistence. I've had no luck beating cross origin policy up to this point using $.getJSON.
$(document).ready(function(){
var data;
var g = $.getJSON('../data.JSON', function(d){
console.log(d);
data = d;
});
console.log(data)
d = proper JSON object,
data = undefined
I have no idea why...
javascript in your case is working only on client side and you cannot modify any file on client's machine.
Alternative solutions:
Use a server, if you are familiar with javascript, you can use node.js. Though it has a learning curve and you might take some time in learning that.
Download updated JSON file and replace original file with this new file. you can create files in javascript and download them on client machine. Then you have to manually replace original file.

Reading local XML file with javascript

I am new to HTML/Javascript, as well as coding in general so bear with me :). I am trying to create a "Spot the Difference" game in html5 using javascript. Everything is local (on my machine). I have two pictures, of the same size, one with differences. To generate data about the clickable fields, I have a java program that reads both of the images and outputs all of the positions in which pixels are different into a XML file. My plan was to then use this XML file with my javascript to define where the user could click. However, it appears (correct me if I'm wrong) that javascript cannot read local XML files for security reasons. I do not want to use an ActiveXObject because I plan on putting this onto mobile devices via phone gap or a webkit object. Does anyone have a better approach to this problem, or perhaps a way to read local XML files via javascript? Any help would be greatly appreciated, thanks.
If you are planning to put this into a smart phones (iOS and Android) and read local files, I have done similar things with JSON (yes, please don't use XML).
Convert your output to JSON
Put this as part of your application package. For example, in Android, I put it as part of the .apk in /appFiles/json
Create a custom content provider that would read the local file. I create mine as content:// but you create whatever scheme you want. You could leverage android.content.ContentProvider in order to achieve custom URL Scheme. iOS has its own way to create custom scheme as well. The implementation simply read your local storage and give the content
To read it from Javascript, I simply call ajax with the custom scheme to get the json file. For example content://myfile/theFile.json simply redirect me to particular directory in local storage with /myfile/theFile.json appended to it
Below is the sample to override openFile() in the ContentProvider
public ParcelFileDescriptor openFile (Uri uri, String mode) {
try {
Context c = getContext();
File cacheDir = c.getCacheDir();
String uriString = uri.toString();
String htmlFile = uriString.replaceAll(CUSTOM_CONTENT_URI, "");
// Translate the uri into pointer in the cache
File htmlResource = new File(cacheDir.toString() + File.separator + htmlFile);
File parentDir = htmlResource.getParentFile();
if(!parentDir.exists()) {
parentDir.mkdirs();
}
// get the file from one of the resources within the local storage
InputStream in = WebViewContentProvider.class.getResourceAsStream(htmlFile);
// copy the local storage to a cache file
copy(in, new FileOutputStream(htmlResource));
return ParcelFileDescriptor.open(htmlResource, ParcelFileDescriptor.MODE_READ_WRITE);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
I hope it helps
I would suggest modifying your java program to output a JSON formatted file instead of XML. JSON is native to JavaScript and will be much simpler for you to load.
As for actually loading the data, i'm not sure what the best option is as you say you want to evenutally run this on a mobile device. If you were just making a normal website you could setup a web server using either Apache or IIS depending on your OS and put the files in the document root. Once you've done that you can load the JSON file via Ajax, which can easily be googled for.
Not sure if this helps any.
Since this is a local file, you can do this with jQuery
$.ajax({
type: "GET",
url: "your.xml",
dataType: "xml",
success: function(xml){
///do your thing
}
});
http://api.jquery.com/jQuery.ajax/

Categories

Resources