0

Is there a way to create and write data to a file using javascript/jquery. I referred this link https://gist.github.com/Arahnoid/9925725#file-read-write-file-js . But it gives me error for tis line

var file = new File("E:/abc/sample.txt); 
 error: NS_ERROR_FAILURE: in firefox
sugar
  • 251
  • 4
  • 13

2 Answers2

1

You can't write files in javascript using your browser without asking the user for permission first.

you can prompt the user to save a file using the following liberary:

https://github.com/eligrey/FileSaver.js

POC code:

<script src="FileSaver.js"></script>
<script>
    var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
    saveAs(blob, "hello world.txt");
</script>

This will prompt the user to save "Hello world!" to the file "Hello, world.txt" file.

0

Javascript is client side language which runs on server, and it doesn't have access to client file system, I don't know what your exact requirement is but this might help you

http://tutorialzine.com/2011/05/generating-files-javascript-php/ https://github.com/eligrey/FileSaver.js

Would you let me know what is your exact requirement then I might help you

Parag Bhayani
  • 3,280
  • 2
  • 28
  • 52
  • i want to introduce a save as draft feature in my form. hence i thought of having a button as draft on click of which it converts the form data to json and i would write this json data to a file on some server . Later when the user wishes to continue filling the remaining form i thought i could read the saved json data and populate the html form fields. – sugar Jun 02 '15 at 14:54
  • That is quite simple thing you don't need to write it on file for this.. You could save JSON string on user's localStorage variable and can use it from there. Another option is of saving information in cookies, For you requirement I would suggest you to use localStorage, As it is supported by all major browsers and it is quite straight forward ______ you can have a look at this link for more information http://www.w3schools.com/html/html5_webstorage.asp and google it for localstorage – Parag Bhayani Jun 03 '15 at 06:02