Accessing local files via ActiveXObject is quite easy, but using Firefox browser got me stuck with “undefined” errors and lead to Mozilla workarounds.
Following JS script accesses local file content and prints out to FireBug console:
function readFile(srcfile) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
} catch (e) {
alert("Permission to read file was denied.");
}
var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath( srcfile );
if ( file.exists() == false ) {
alert("File does not exist");
}
var is = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance( Components.interfaces.nsIFileInputStream );
is.init( file,0x01, 00004, null);
var sis = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance( Components.interfaces.nsIScriptableInputStream );
sis.init( is );
var output = sis.read( sis.available() );
console.log(output);
}
Note, that Firefox will prompt the user whether it’s allowed to execute any local operations via JavaScript.
Read File Original from
Andrey Vystavkin Blog.