How to save string from input to existing text JAVASCRIPT

I have html page, on that page I have input and button

I want to save the string in input into existing file like ‘text.txt`

this is my html code

<input id="sub" dir="ltr" type="text" placeholder="type something">
<button id="myBtn" onclick="myFunction()" class="main-btn">Subscribe</button>

and this is my javascript function

    function myFunction() {
        const fs = require('fs')
        let data = document.getElementById("sub").value + "rn";
        fs.writeFile('Output.txt', data, (err) => {
            if (err) throw err;

but it’s not working


You can’t just access the Filesystem from your browser. Your options depend on what you are trying to achieve.

1. Save a txt file on the users local filesystem

You can create a “downloadable” element directly from JS. Depending on the browser the user will be prompted to allow downloads and/or where to store the file. You cannot access the file afterwards.

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename); = 'none';


// Start file download.
download("hello.txt","This is the content of my file :)");


2. Save data inside the browser so you can read/write whenever the users visits your website

The localstorage API can create small keyed objects (like 5-10 mb) on the user system. You can read/write anything to or from it that is serializable.

localStorage.setItem('myCat', 'Tom');
const cat = localStorage.getItem('myCat');


3. Save a file/data on your server

If you need the file on the server itself, you must create a backend with php, nodejs etc. Then you must implement an endpoint that accepts the data you want to save and inside nodejs you can import the “fs” and directly write files to it.

const fs = require('fs')

const content = 'Some content!'

fs.writeFile('/Users/joe/test.txt', content, err => {
  if (err) {
  //file written successfully