miladjurablu
miladjurablu

Reputation: 17

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

<script>
    function myFunction() {
        const fs = require('fs')
        let data = document.getElementById("sub").value + "\r\n";
        fs.writeFile('Output.txt', data, (err) => {
            if (err) throw err;
        })
    }
</script>

but it's not working

Upvotes: 0

Views: 952

Answers (1)

adroste
adroste

Reputation: 887

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);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

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

Source: https://www.codegrepper.com/code-examples/javascript/javascript+download+text+as+txt+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');
localStorage.removeItem('myCat');

Here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

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) {
    console.error(err)
    return
  }
  //file written successfully
})

Source: https://nodejs.dev/learn/writing-files-with-nodejs

Upvotes: 2

Related Questions