'How to target the contents inside a text blob?

I'll keep it short. The following is the method I'm using in order to convert the text inside a textarea tag to a .txt file:

<textarea id="inputTextToSave"></textarea>

 

<button onclick="saveTextAsFile()">SAVE</button>

<textarea id="string"></textarea>

<script>

function saveTextAsFile()

{
    var textToWrite = document.getElementById("inputTextToSave").value;
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain;charset=utf-8'});
    


document.getElementById("string").innerHTML= textFileAsBlob.txt;
}

    </script>

The issue is whenever I run the function and try to insert the blob content from 'inputTextToSave' textarea in the 'string' textarea, it doesn't render the text. Essentially I'm trying to target the contents inside the blob so that I can later upload them to a database and that db only accepts .txt files. Any help would be appreciated. Thanks!



Solution 1:[1]

Try to use await textFileAsBlob.text() to convert blob to string (don't forget to declare your function as async to use await method, because Blob.text() method returns Promise, not the actual result).

Example:

import { Blob } from 'buffer';

const textFileAsBlob = new Blob(['xxxx'], {type:'text/plain;charset=utf-8'});
console.log(`textFileAsBlob = ${textFileAsBlob}`)

const stringFromBlob = await textFileAsBlob.text()
console.log(`stringFromBlob = ${stringFromBlob}`)

Result: enter image description here

Docs: https://developer.mozilla.org/en-US/docs/Web/API/Blob/text

Code Snippet based on your code:

async function saveTextAsFile() {
    const textToWrite = document.getElementById("inputTextToSave").value;
    const textFileAsBlob = new Blob([textToWrite], {type:'text/plain;charset=utf-8'});
    document.getElementById("string").innerHTML= await textFileAsBlob.text();
}
<textarea id="inputTextToSave"></textarea>
<button onclick="saveTextAsFile()">SAVE</button>
<textarea id="string"></textarea>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1