1

Please I need help to edit a txt file in client side, I can't find a good method. I need update the data automatic, without confirmation, like it:

 <button onclick="updatefile()">Update</button>
   <script>
      functiom updatefile(){
         var file = "d:\test.txt"          
         var data = //here any function for load all data from file
         ...
         ...
         data .= " new data to add";

         //here any function for save data in test.txt  
         .....
      }
</script>

Please help me.

CodeWithCoffee
  • 1,896
  • 2
  • 14
  • 36
marjes
  • 172
  • 15
  • 2
    You can read a local file using the [File Web API](https://developer.mozilla.org/en-US/docs/Web/API/File), but there is no way to automatically save back to a file from a browser (for security reasons). – Dave Mar 25 '15 at 22:31

1 Answers1

0

You cannot do this in that manner using JS. What you CAN do though is to download it on the client, without having the server intervene by using data urls.

Setting the name of said downloaded file is not cross browser compatible unfortunately...

HTML

<textarea id="text" placeholder="Type something here and click save"></textarea>
<br>
<a id="save" href="">Save</a>

Javascript

// This defines the data type of our data. application/octet-stream
// makes the browser download the data. Other properties can be added
// while separated by semicolons. After the coma (,) follows the data
var prefix = 'data:application/octet-stream;charset=utf-8;base64,';
$('#text').on('keyup', function(){
  if($(this).val()){
    // Set the URL by appending the base64 form of your text. Keep newlines in mind
    $('#save').attr('href', prefix + btoa($(this).val().replace(/\n/g, '\r\n')));
    // For browsers that support it, you can even set the filename of the 
    // generated 'download'
    $('#save').attr('download', 'text.txt');
  }else{
    $('#save').removeAttr('href');
    $('#save').removeAttr('download');
  }
});
Loupax
  • 4,728
  • 6
  • 41
  • 68
  • is possible select a custom directory for save the file?, or always the file is stored in google chrome directory – marjes Mar 26 '15 at 17:01
  • As far as I know, there is no way to do this. It's up to the browser. If your app is a web application you can temporary store your text in local storage, but you'll have to go through a download to actually get the file. – Loupax Mar 26 '15 at 22:57
  • If your application is a packaged app (like a chrome extension or a stand-alone chrome app) you might be able to save files to a sandbox filesystem but I haven't used it personally. Related question: http://stackoverflow.com/questions/21213397/where-is-the-file-sandbox-for-a-chrome-app – Loupax Mar 26 '15 at 23:00