Home > Enterprise >  How to write to a file from a javascript function after clicking on a button in html
How to write to a file from a javascript function after clicking on a button in html

Time:08-07

I'm trying to write really basic code where after a button press on an html file, a .txt file is written locally through a javascript function. Is this impossible to do? I can write to a file with just the javascript file but not when trying with both.

<!DOCTYPE html>
<html>
  <head>
    <title>Tic Tac Toe</title>   
    <script type = "text/javascript" src="test.js"></script>  
  </head>
  <body>
    <input type="button" onclick="javascript: myFunction()" value="Display"/>
  </body>
</html>
index.html

function myFunction() {
    const fs = require('fs')
  
// Data which will write in a file.
    let data = "Learning how to write in a file."
  
// Write data in 'Output.txt' .
    fs.writeFile('output.txt', data, (err) => {
      
    // In case of a error throw err.
        if (err) throw err;
    })

  }

test.js

CodePudding user response:

You can use the File API, which implements the Blob API, like this

const writeToTextFile = (text, fileName) => {
  let textFile = null;
  const makeTextFile = (text) => {
    const data = new Blob([text], {
      type: 'text/plain',
    });
    if (textFile !== null) {
      window.URL.revokeObjectURL(textFile);
    }
    textFile = window.URL.createObjectURL(data);
    return textFile;
  };
  const link = document.createElement('a');
  link.setAttribute('download', fileName);
  link.href = makeTextFile(text);
  link.click();
};

const data = 'Learning how to write in a file.';
writeToTextFile(data, 'output.txt');

CodePudding user response:

If you are planning use browser to create into a server a file directly, it hopefully is not possible. Imagine someone malicious send a script with instructions to erase all server, for instance.

 const fs = require('fs')

this is a library to usage into a server side, node js create locally files because it is a server side engine.

So, the correct flow is, your browser make a request to a server, in server side you validate that request, so create a file.

  • Related