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.
Related
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.
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();
I could not find out why this part of my code doesn't work:
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
var FilePath = dir + "/" + FileName;
var file = new File("FilePath");
var reader = new FileReader();
reader.onload = function(e) {FileText = reader.result;}
reader.readAsText(file);
alert (FileText);
The intention is, I think, clear: FilePath contains the filename of a file (passed via parameter FileName) containing logging data (a plain ASCII text file, with one line per log entry), the file is located in the same directory as the web page is (loc), and I want to embed the text into my html document somewhere further down the code.
Since the logged lines are of different kinds (e.g. errors, warning, other blabla ...) each line needs to be parsed and processed.
I intended to split FileText into an array, and loop through it. I cannot, however, get readastext to work. Though, according to FireFox debugger, FilePath does contain the correct string, I get the NS_ERROR_FAILURE, which I, according to the sparse documentation I found about it, must consider to be the 'zillionst stupid way to say "File not found".
I found tons of other posts from people messing with the file API, and tons of snippets taken from the mozilla docs which don't help me out. I read that there are maybe other ways to read a file, e.g. through Ajax, JQuery ... but before I go that way ... is it really, really absolutely impossible to accomplish what I want using just plain JavaScript, and if it is possible, who can provide a code snippet?
Thanks very much,
Armin.
You have quotes around "FilePath":
var file = new File("FilePath");
This means it's going to try to load a file with the path "FilePath".
Pretty sure this is what you want:
var file = new File(FilePath);
On the other hand, Quentin is absolutely right. You're not going to be able to access local files if this code is running in a web page.
Since you are using window.location.pathname i assume that you are in a browser and want to use that code to "navigate" to files on the server based on the URL path.
I think your whole approach is wrong, and it would be a security issue to have something like that possible.
The File API can be used strictly on files selected by the user, and not on any file. The MDN description is self-explanatory:
Using the File API, which was added to the DOM in HTML5, it's now possible for web content to ask the user to select local files, then read the contents of those files. This selection can be done by either using an HTML element, or by drag and drop.
Yes, you can specify a path to any file in the File constructor method, but that doesn't mean you can access any file. Another excerpt from MDN:
This only works from privileged code, so web content can't do it. This protects users from the inherent security risks associated with allowing web content free access to the contents of their disks. If you pass a path to the File constructor from unprivileged code (such as web content), an exception will be thrown.
This code did the trick:
var objXMLhttp = new XMLHttpRequest()
objXMLhttp.open("GET",strFileName,true);
objXMLhttp.send();
and, in addition, an objXMLhttp.onreadystatechange=function() ... event handler must be implemented, which is the code acutally receiving the data, like so:
objXMLhttp.onreadystatechange=function()
{
if (objXMLhttp.readyState==4 && objXMLhttp.status==200)
{
var arrContents = objXMLhttp.responseText.split("\n"); // gotcha!
....
}
}
Easy win is to do an ajax request for the path...you should have your page that contains the js and files served by a web server. Any other way needs other priveleges and if you were to get files from a users computer without an uploader or anything like that would be a security breach
I want to download folder that client side (browser) make.
I considered using File API, but I can't find how to make folder.
For example, some png make from html canvas put one folder, I want to save this folder with download dialog.
I want to use a folder for some file to one folder.and I must download only once.
Please advise me.
html
<a download='folder' href='#' onclick="Download()">download</a>
You can use FSO.js, but be warned that it currently only works in Chrome. Additionally, the folders you create can only really be accessed from within your webapp (for example, you can't choose to write a specific folder on the C drive).
Firstly, You can't really interact with the local system or the server with JavaScript because of security. You can call a server-side script with JavaScript, via AJAX.
If you don't care, you can check out Javascript FSO CreateFolder Method
JavaScript Example...
// initialize ActiveXObject and create an object of Scripting.FileSystemObject.
var fso = new ActiveXObject("Scripting.FileSystemObject");
// creates a folder with specified name at the specified location
fso.CreateFolder("C:\\Temp\\myFolder");
fso = null;
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/