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
5
  • 3
    JS (unless used on the server, node.js) doesn't have access to the file system. So, No. Commented Jun 2, 2015 at 14:04
  • not using a browser as the client Commented Jun 2, 2015 at 14:05
  • similar to stackoverflow.com/questions/21012580/… Commented Jun 2, 2015 at 14:06
  • @tymeJV Does not the last Javascript Api provide some simple ways for accessing filesystem? Commented Jun 2, 2015 at 14:06
  • @reporter The File APIs are now deprecated Commented Jun 2, 2015 at 14:14

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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.
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 w3schools.com/html/html5_webstorage.asp and google it for localstorage

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.