Preeti padalia
Preeti padalia

Reputation: 3

how to use component.classes in javascript to access local files?

I tried a solution to read write a local file in firefox by this function

function Read(file) {
    var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
    var scriptableStream = Components.classes["@mozilla.org/scriptableinputstream;1"].getService(Components.interfaces.nsIScriptableInputStream);
    var channel = ioService.newChannel(file, null, null);
    var input = channel.open();
    scriptableStream.init(input);
    var str = scriptableStream.read(input.available());
    scriptableStream.close();
    input.close();
    return str;
}

but in firefox, execution exited at var ioService=Components.classes["@mozilla.org/network/io-service;1"]. Please tell how to use this code. Do I need to install any plugins? I am using FF version 23.0.1. I am new to this. Any help will be greatly appreciated.

Upvotes: 0

Views: 1302

Answers (1)

Jacob
Jacob

Reputation: 78860

Imagine if any web page on the Internet could read any file on your local file system. If that were possible, then it would be very easy for malicious programmers to steal private information from us. Fortunately, web browsers running HTML pages do not have the ability to do this directly.

If you need to read a file on the user's computer for legitimate reasons, you could use the HTML5 File API. This will work a little differently, however, since it will require the user to first select the XML file before you can read it. Perhaps your page could give them instructions so they know how to get to the proper file.

If you have to both read and write a file, you're going to have to use a different technology than HTML+JS. One Mozilla-specific option is for you to write a XUL application. The JavaScript code you have above, which uses their proprietary XPCOM system, will execute in a XUL application, given that it has the right permissions. If this is the route you want to go, MDN has some good resources.

If you don't want to dive into XUL, there are any number of scripting languages or desktop application development tools you can use and have the user run on their desktop. Without knowing the specifics of what you need to do, I can only give you this generic answer.

I hope this helps. Sorry that you'll have to abandon your current approach.

Upvotes: 1

Related Questions