How to read and write into file using JavaScript?

How to read and write into file using JavaScript?

Can anybody give some sample code to read and write a file using JavaScript?


Solution 1:

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

Edit: That link was to the Sun docs that now have been moved by Oracle.

To keep up with the times here’s the node.js documentation for the FileSystem class:

Edit(2): You can read files client side now with HTML5:

Solution 2:

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

Solution 3:

The future is here! The proposals are closer to completion, no more ActiveX or flash or java. Now we can use:

Related:  Expected an assignment or function call and instead saw an expression

You could use the Drag/Drop to get the file into the browser, or a simple upload control. Once the user has selected a file, you can read it w/ Javascript:

Solution 4:

here’s the mozilla proposal

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

for more complex file operations in rhino, you can use 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.

Solution 5:

This Javascript function presents a complete “Save As” Dialog box to the user who runs this through the browser. The user presses OK and the file is saved.

Edit: The following code only works with IE Browser since Firefox and Chrome have considered this code a security problem and has blocked it from working.

// content is the data you'll write to file<br/>
// filename is the filename<br/>
// what I did is use iFrame as a buffer, fill it up with text
function save_content_to_file(content, filename)
    var dlg = false;
           open("text/plain", "replace");
           charset = "utf-8";
           document.charset = "utf-8";
           dlg = execCommand('SaveAs', false, filename+'.txt');
    return dlg;

Invoke the function:

save_content_to_file("Hello", "C:\\test");

Solution 6:

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.

Related:  window.onunload is not working properly in Chrome browser. Can any one help me?

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