Based on the other answers on this site, I already feel like I know the answer to this question, but, as it's slightly different, I wanted to ask.
Is it possible to access local files from JavaScript that is running locally on the machine (AKA, my website address will be file:///C:/...)? Or, is this sandboxed as well?
What I am trying to do: I have a standalone computer that I want people to be able to drop in JSON or XML files into a local folder which are read in at the creation of the site and used to generate a single web page. If the JavaScript solution is not possible, can you provide any other suggestions?
Thank you.
Web browsers (and JavaScript) can only access local files with user permission. To standardize file access from the browser, the W3C published the HTML5 File API in 2014. It defines how to access and upload local files with file objects in web applications.
You can't modify local files from Javascript.
The MoveFile() method is used to move a file from a source to a destination. This method takes two parameters. The first parameter, source, is the location of the file to be moved, while the second parameter, destination, is the new location of the moved file.
A webpage can read any file on the same server as it was loaded from (this is the cross-site policy of JavaScript). That means that the page file:///C:/mywebsite/index.html can read the file file://C:/somedir/somefile.xml. To read this file, either use ajax, load it in an iFrame or load it as a javascript or css file.
Several browsers support custom methods for loading local file (and other interesting things), IE has activeX and Firefox has XPCOM.
According to the Firefox documentation, the following code will work:
var req = new XMLHttpRequest();
req.open('GET', 'file:///home/user/file.json', false);
req.send(null);
if(req.status == 0)
dump(req.responseText);
I seem to recall it only works within the same directory as the HTML page. And I don't know if this will work in other browsers.
This will only work on IE, but if that is not a problem for you, here is some sample code to write to a file:
var fso, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
s = fso.OpenTextFile("c:\\path\\to\\myfile.txt" , 8, 1, -2);
s.writeline("Hello World");
s.Close();
And then to read from it:
f = fso.OpenTextFile(filename, ForReading);
while (!f.AtEndOfStream) {
var r = f.ReadLine();
document.write (r + "<br />");
}
f.Close();
For more information about OpenTextFile, check out: http://msdn.microsoft.com/en-us/library/314cz14s(VS.85).aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With