Read local text file using js/html file on on local machine - javascript

I've built a simple html page with javascript in a separate file, called on a button press.
I've opened the html file in chrome, and the path resembles: file:///home/tom/projects/index.html
The javascript needs to read a JSON file (file:///home/tom/projects/mydata.json) which is in the same directory, using a hardcoded path.
I'm really struggling to do this. As I understand, this is because I'm using client side js (meaning I can't use the fs library for example), which is limiting my options.
According to the question here, I can't load the file if I use the URL in the format: file:///home/to.... as it gives me the error:
Cross origin requests are only supported for protocol schemes: HTTP, data, chrome, chrome-extension, https.
If I start an HTTP-server, as the answer suggests, I can use server-side modules, but if possible I would like to avoid this.
I've noticed many answers that suggest using a dialog box like this:
var selectedFile = document.getElementById('input').files[0];
function readFile (file_path) {
var reader = new FileReader();
reader.readAsText(file_path);
console.log(reader.substring(0, 100));
};
but I can't make this work with a path in the form: file:///home/tom/projects/mydata.json
Is there a way to load a .json file from a file:///home/to.... format URL using client-side javascript, with a hardcoded path (ie not asking the user to select the file from a selection box)?

This is a deliberate security restriction, to stop a user from being given, and then opening, a HTML page which then tries to read their disk.
Run your page in a webserver (as that question suggested) then you can either load the JSON from a URL (e.g. something like http://localhost/projects/mydata.json) using JavaScript, or use a server-side language to fetch it and display it inside the rendered HTML. Either way will work, the first way is probably simpler and closest to what you've got now.
It's always far better to serve HTML pages from a HTTP server, the way it's intended to be.

Related

How can i read local file from D drive in javascript

My requirement is to read the json file which contains some data and store in some other .js file.
I got task to read local file from local disk in Javascript , i have used file path like - D:\json\analytics.json.
(document).ready(){
($).getData("D:\json\analytics.json");
}
when i see in firebug it takes other url.
How I can do it, is it possible to read file from javascript.
I don't know javascript , i have seen some answer but i am not able to understand .
Need Solution , how I can achieve it. is there any other way to read file on jsp without using scriptlet . From server side , can send it on the jsp page.
I think Jaronmanda's answer won't work cause it will hit cross origin issue, see "Cross origin requests are only supported for HTTP." error when loading a local file.
As the page suggested, in general you need to serve that json file from a web service (same domain, or allow your domain to access), but it depends on what you really need to do. If you can control where that json file is stored, the easier way is to put that in a subdirectory of your html file, and do:
$(document).ready(function () {
$.get('<directory>/analytics.json', function (data) {
// Do your stuff
});
});

Again: how can I read a file using javascript

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

Javascript Read Text File Offline

Currently I use this code to read a txt file with words and perform some operations. However, this particular code requires the html to be deployed on a server. Is there any workaround where I can replace this code with something else to read the file without the need of a server?
var xhr = new XMLHttpRequest();
xhr.open( "GET", "dictionary.txt", false );
xhr.send( null );
var words= xhr.responseText.split(",");
It is NOT possible to call Ajax outside your server domain (except you use scriptagproxy, that too requires you to have some server side configuration). So, in short, you CANNOT read files on your local computer using Ajax calls.
You might like this article.
The file selection can be made either by input or drag-and-drop (not otherwise). Please see: this
You cannot read files from the clients' computer, so the text file you are reading must be on the same server as your javascript.
However, if you are loading the HTML file from your computer (e.g. file://c:/../test.html), you might be able to read files located on ONLY your computer by using relative paths.
You can hide an iframe on the page, with its src='dictionary.txt',
and read or manipulate the iframe's local content when it's onload event fires.

What is a "?" for in the src attribute of a html script tag?

If this has been asked before, I apologize but this is kinda of a hard question to search for. This is the first time I have come across this in all my years of web development, so I'm pretty curious.
I am editing some HTML files for a website, and I have noticed that in the src attribute of the script tags that the previous author appended a question mark followed by data.
Ex: <script src="./js/somefile.js?version=3.2"></script>
I know that this is used in some languages for value passing in GET request, such as PHP, but as I far as I ever knew, this wasn't done in javascript - at least in calling a javascript file. Does anyone know what this does, if anything?
EDIT: Wow, a lot of responses. Thanks one and all. And since a lot of people are saying similar things, I will post an global update instead of commenting everyone.
In this case the javascript files are static, hence my curiosity. I have also opened them up and did not see anything attempt to access variables on file load. I've never thought about caching or plain version control, both which seam more likely in this circumstance.
I believe what the author was doing was ensuring that if he creates version 3.3 of his script he can change the version= in the url of the script to ensure that users download the new file instead of running off of the old script cached in their browser.
So in this case it is part of the caching strategy.
My guess is it's so if he publishes a new version of the JavaScript file, he can bump the version in the HTML documents. This will not do anything server-side when requested, but it causes the browser to treat it as a different file, effectively forcing the browser to re-fetch the script and bypass the local cache of the file.
This way, you can set a really high cache time (like a week or a month!) but not sacrifice the ability to update scripts frequently if necessary.
What you have to remember is that this ./js/somefile.js?version=3.2 doesn't have to be a physical file. It can be a page which creates the file on the fly. So you could have it where the request says, "Hey give me version 3 of this js file," and the server side code creates it and writes it to the output stream.
The other option is to force the browser to not cache the file and pull down the new one when it makes the request. Since the URI changed, it will think the file is completely new.
A (well-configured) web server will send static files like JavaScript source code once and tell the web browser to cache that file locally for a certain period of time (could be a day, a week, a month, or longer). When the browser sees another request for that same file, it will just use that version instead of getting new code from the server.
If the URL changes -- for example by adding a query string -- then the browser suspects that its cached version is no good and gets a new one. As such, the ? helps developers say "Oops, I changed this file, make sure the browser gets a new copy."
In this case it's probably being used to ensure the source file isn't cached between versions.
Of course, it could also be used server side to generate the javascript file, without knowing what you have on the other end of the request, it's difficult to be definitive.
BTW, the ?... portion of the url is called the query string.
this is used to guarantee that the browser downloads a new version of the script when available. The version number in the url is incremented each time a new version is deployed so that the browser see it as a different file.
Just because the file extension is .js doesn't mean that the target is an actual .js file. They could set up their web server to pass the requested URL to a script (or literally have a script named somefile.js) and have that interpret the filename and version.
The query string has nothing to do with the javascript. Some server side code is hosting up a different version depending on that querystring it appears.
You should never assume anything about paths in a URL. The extension on a path in a URL doesn't really tell you anything. URLs can be completely dynamic and served by some server side code or can rewritten in web servers dynamically.
Now it is common to add a querystring to urls when loading javascript files to prevent client side caching. If the page updates and references a new version of the script then the page can bust through and cause the client to refresh it's script.

Ajax Parsing Local XML

I'm building a local html file to show dynamically some data from an XML file and by using Chrome's Inspector I figured my XML file is not being parsed because it is "not hosted on a webserver"
XMLHttpRequest cannot load data.xml. Cross origin requests are only supported for HTTP.
I know that there are a few flags I could pass to Chrome/web browser to workaround this limitation but I'm looking into some alternative method. I will probably have to distribute this files to a few people and teaching them how to pass flags to the browser is not an option for me. Hosting them on a web server is not an option either.
Thanks a lot in advance.
No ghost unless you set up a local server or host the XML file locally. Ajax has to follow the same origin policy.
If you're willing to use a library you can use jQuery's AJAX method to perform a cross-domain request (i'm not entirely certain that jQuery will support what you're trying to do). JSONP works, but you have XML data...
You could try loading it in a script tag anyway and see if you can get the innerHTML value without breaking the script; once you're done getting the text from it, remove the script from the page. You may be able to get at the data before the browser tries to parse the script by attaching onload and onreadystatechange events to the script element.
var s = document.createElement('script');
s.src = '/path/to/file.xml';
s.onload = s.onreadystatechange = getData;
function getData(e)
{
//get the text out of the script element
//remove the event handler from the script element
//remove the script from the page
}
document.getElementsByTagName('body')[0].appendChild(s);
I didn't test it, but it might work.
How about setting up a local webserver? XAMPP should be easy to install even for novice. Just tell them to put your files in the htdocs folder, run xampp and start the apache server.
Unless there's a compelling reason to have a separate html and xml file, you could just put the data directly in the html file.
I'm afraid if chrome only provides options that you don't like to apply, your application and chrome will not come together. Access via iframe & object does'nt work too, load()-method of createDocument is not supported by chrome(if it does I guess you got the same error).
Whatever you try will be a sideway to pass chrome's restrictions, what cannot be good, because I think they have good reasons to setup these restrictions.

Categories

Resources