Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to use a JavaScript in simple math equation but place results in a text file?

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading