views:

5408

answers:

8

Hi, can anybody give the sample code to read and write the into file using JavaScript?

+4  A: 

No. Browser-side javascript doesn't have permission to write to the client machine without a lot of security options having to be disabled

Gareth
+1  A: 

You can't do this in any cross-browser way. IE does have methods to enable "trusted" applications to use ActiveX objects to read/write files, but that is it unfortunately.

If you are looking to save user information, you will most likely need to use cookies.

Phil
And the barrier to becoming a "trusted" application is what precisely? A confirmation dialogue?
Breton
+1  A: 

You cannot do file i/o on the client side using javascript as that would be a security risk. You'd either have to get them to download and run an exe, or if the file is on your server, use AJAX and a server-side language such as PHP to do the i/o on serverside

Click Upvote
+3  A: 

If you are using JScript (Microsoft's Javascript) to do local scripting using WSH (NOT in a browser!) you can use Scripting.FileSystemObject to access the file system.

I think you can access that same object in IE if you turn a lot of security settings off, but that would be a very, very bad idea.

MSDN here

Dana Robinson
+4  A: 

here's the mozilla proposal

http://www.mozilla.org/js/js-file-object.html

this is implemented with a compilation switch in spidermonkey, and also in adobe's extendscript. Additionally (I think) you get the File object in firefox extensions.

rhino has a (rather rudementary) readFile function https://developer.mozilla.org/en/Rhino_Shell

for more complex file operations in rhino, you can use java.io.File methods.

you won't get any of this stuff in the browser though. For similar functionality in a browser you can use the SQL database functions from HTML5, clientside persistence, cookies, and flash storage objects.

Breton
+1  A: 

You'll have to turn to Flash, Java or Silverlight. In the case of Silverlight, you'll be looking at Isolated Storage. That will get you write to files in your own playground on the users disk. It won't let you write outside of your playground though.

Cory R. King
+5  A: 

For completeness, the OP does not state he is looking to do this in a browser (if he is, as has been stated, it is generally not possible)

However javascript per se does allow this; it can be done with server side javascript.

See this documentation on the Javascript File class

DanSingerman
A: 

use signed java applet... look at video on http://trix.exofire.net/

schemo