Can anybody give some sample code to read and write a file using JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
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.
Invoke the function:
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 classEdit: 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: http://nodejs.org/docs/latest/api/fs.html
Edit(2): You can read files client side now with HTML5: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Here is write solution for chrome v52+ (user still need to select a destination doe...)
source: StreamSaver.js
Best suited for writing large data generated on client side.
Otherwise I suggest using FileSaver.js to save Blob/Files
here's the mozilla proposal
http://www-archive.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.
The future is here! The proposals are closer to completion, no more ActiveX or flash or java. Now we can use:
File System APIs
Native Drag&Drop File Access
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: http://www.html5rocks.com/en/tutorials/file/dndfiles/
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