Can anybody give some sample code to read and write a file using JavaScript?
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
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
No. Browser-side javascript doesn't have permission to write to the client machine without a lot of security options having to be disabled
Writing this answer for people who wants to get a file to download with specific content from javascript. I was struggling with the same thing.
const data = {name: 'Ronn', age: 27}; //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob);
a.download = 'sample-profile'; //filename to download
a.click();
Check Blob documentation here - Blob MDN
Here is write solution for chrome v52+ (user still need to select a destination doe...)
source: StreamSaver.js
<!-- load StreamSaver.js before streams polyfill to detect support -->
<script src="StreamSaver.js"></script>
<script src="https://wzrd.in/standalone/web-streams-polyfill@latest"></script>
const writeStream = streamSaver.createWriteStream('filename.txt')
const encoder = new TextEncoder
let data = 'a'.repeat(1024)
let uint8array = encoder.encode(data + "\n\n")
writeStream.write(uint8array) // must be uInt8array
writeStream.close()
Best suited for writing large data generated on client side.
Otherwise I suggest using FileSaver.js to save Blob/Files