Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is possible to save JavaScript variable as file? [duplicate]

Tags:

javascript

Is there a way to convert a string from a JavaScrip variable, into a downloadable file that users can download when clicking a button ?

Thanks for any advice.

<div id="txt">Lorem Ipsum</div> <br /> <button id="test">Download text as file !</button> 
like image 739
dabraham Avatar asked Jul 22 '14 21:07

dabraham


People also ask

How do I copy a variable from one JavaScript file to another?

To import a variable from another file in JavaScript:Export the variable from file A , e.g. export const str = 'Hello world' . Import the variable in file B as import { str } from './another-file.

Are JavaScript variables stored in memory?

“Variables in JavaScript (and most other programming languages) are stored in two places: stack and heap. A stack is usually a continuous region of memory allocating local context for each executing function.

Can JavaScript create a file?

Did you know you can create files using JavaScript right inside your browser and have users download them? You can create files with a proper name and mime type and it only takes a few lines of code.

Can a variable have two values JavaScript?

There is no way to assign multiple distinct values to a single variable. An alternative is to have variable be an Array , and you can check to see if enteredval is in the array. To modify arrays after you have instantiated them, take a look at push , pop , shift , and unshift for adding/removing values.


1 Answers

Yes it is, you could do something like this in HTML5, using the download attribute

function download_txt() {   var textToSave = document.getElementById('txt').innerHTML;   var hiddenElement = document.createElement('a');    hiddenElement.href = 'data:attachment/text,' + encodeURI(textToSave);   hiddenElement.target = '_blank';   hiddenElement.download = 'myFile.txt';   hiddenElement.click(); }  document.getElementById('test').addEventListener('click', download_txt); 

FIDDLE

like image 130
adeneo Avatar answered Sep 20 '22 18:09

adeneo