I’m truly a newbie at any of this.
Anyway, I’m trying to put the results of this simple JavaScript into a txt file
Example script:
var numOne=25, numTwo=14,res;
res = numOne – numTwo;
document.write(” ” + res + “”);
I want to create a txt file and put the results in it, instead of showing the results
I tried to change the document.write but i have no idea what i was doing
>Solution :
In general Javascript deliberately does not make it easy to create a file
This is because it is a security risk. Javascript generally doesn’t have access to your computer’s file system.
However, you can create a file and make it download
const result = 3 + 4
const link = document.createElement("a");
const file = new Blob([result], {
type: 'text/plain'
});
link.href = URL.createObjectURL(file);
link.download = "result.txt";
link.click();
URL.revokeObjectURL(link.href);
Your browser will probably prevent the download from happening if you click the "Run code snippet" button.
So another way to make it run is to press CONTROL-SHIFT-i, which reveals reveals the console.
Into that copy and paste the code. That should trigger a download of the result file.