Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I write files with HTML5/JS?

I wonder if there is any way I can write to files from HTML5/JS? In the broswer ...

like image 390
Jiew Meng Avatar asked Nov 30 '10 02:11

Jiew Meng


People also ask

Can you write files with JavaScript?

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.

Can JS edit files?

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.

Can JavaScript read and write local files?

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.

How do I write a node js file?

The easiest way to write to files in Node.js is to use the fs.writeFile() API.


3 Answers

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&#10;">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 || '');
}
like image 117
ecmanaut Avatar answered Oct 30 '22 01:10

ecmanaut


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

like image 26
mike Avatar answered Oct 30 '22 03:10

mike


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/

like image 31
Pankaj Parashar Avatar answered Oct 30 '22 02:10

Pankaj Parashar