views:

577

answers:

5

hi friends,

How can i write an read a text file in a JavaScript?

Thanks

A: 

You can not access your file system with Java Script, so unfortunately you can't

Svetlozar Angelov
In a *web browser*. JavaScript isn't limited to web browsers.
T.J. Crowder
@Crowder: Technically you are right, but I would assume it *de facto* unless explicitly specified otherwise. I would assume a .NET application is running on Windows unless you tell me it is running on Mono.
Daniel Vassallo
@dnl.vssll: Never assume, it makes an "ass" out of "u" and "me".
Andy E
To further my comment, JavaScript is used very popularly in MANY more places than the web, desktop widgets and shell scripts are just some examples. In all fairness, it's the asker's fault for not being more specific with his/her question.
Andy E
+2  A: 

You can't. JavaScript in the browser has no access to the user's filesystem, by design.

Dave Ward
+3  A: 

You need to run the JS in a host environment that provides an API for accessing the file system.

If you are on Windows, then you can use WSH to achieve this.

JS running a browser, under normal security conditions, cannot access the file system.

David Dorward
A: 

In FF 3.6 it is possible, see my technical example at http://www.bruechner.de/md5file/js/

powtac
+7  A: 

If you are using Firefox, this may help.

//Your text file location on system
var savefile = "c:\\yourtextfile.txt"; 
try {
    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

    var file = Components.classes["@mozilla.org/file/local;1"]
    .createInstance(Components.interfaces.nsILocalFile);
file.initWithPath( savefile );
if ( file.exists() == false ) {
    alert( "Creating file... " );
    file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
}

var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
    .createInstance( Components.interfaces.nsIFileOutputStream );

outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 );
var output = "Your text here";
var result = outputStream.write( output, output.length );
outputStream.close();

alert("Done");
} 
catch (e) {
    alert("Some error occured");
}

It worked for me, hope works for you as well :)

sumit_programmer