I wonder if there is any way I can write to files from HTML5/JS? In the broswer ...
There is a built-in Module or in-built library in NodeJs which handles all the writing operations called fs (File-System). It is basically a JavaScript program (fs. js) where function for writing operations is written. Import fs-module in the program and use functions to write text to files in the system.
JavaScript's File System module provides a way to use JavaScript to access your computer's file system. It can be used to read, create, update, delete and rename files. This can be enormously powerful for editing files that contain data you wish to manipulate.
To read local file (files that stored in machine where browser is installed), you need to use FileAPI, which is not used in current code. To write file to local, it's impossible to write it directly using JavaScript.
The easiest way to write to files in Node.js is to use the fs.writeFile() API.
Assuming your end goal is to let the user save your file somewhere where they will find it, as when right-clicking a link and choosing "Save As...", there isn't wide browser coverage for those APIs yet, likely due to security considerations.
What you can do, however – APIs or not – is cheesing it with a link to a data:
uri with a download
attribute specifying your suggested filename. For instance:
<a id="save" download="earth.txt" href="data:text/plain,mostly harmless ">Save</a>
When clicked, at least in Chrome, this will save a file containing the text mostly harmless
(and a trailing newline) as earth.txt
in your download directory. To set the file contents from javascript instead, call this function first:
function setSaveFile(contents, file_name, mime_type) {
var a = document.getElementById('save');
mime_type = mime_type || 'application/octet-stream'; // text/html, image/png, et c
if (file_name) a.setAttribute('download', file_name);
a.href = 'data:'+ mime_type +';base64,'+ btoa(contents || '');
}
Yes, using the new FileWriter API.
http://www.w3.org/TR/file-writer-api/
You can see the current browser support here: http://caniuse.com/#feat=filesystem
Yes it is possible to read & write files using HTML5+JS.
Link to get you started - Exploring FileSystem API
I also wrote an article a while back for SpeckyBoy on the same topic that you might find useful - http://speckyboy.com/2012/10/30/getting-to-grips-with-the-html5-file-api-2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With