write-to-file

revision:


Content

definition and usage writing to page write to a file from the browser with JavaScript save text to a file in JavaScript checkbox inputs to file save form data to file write form data to file write inputs to file show position information submit input data to text file


definition and usage

top

JavaScript code is usually run from one of two environments: within a web browser when viewing a web page, or in a Node.js environment, which allows JavaScript to be executed outside of a web browser (commonly used for building back-end services and web apps).

Modern JavaScript includes built-in tools to write to a file from the browser. The steps are as follows:

- create a file using the JavaScript Blob object to represent the file;
- create a URL for the new object;
- provide a link which the user can click to tell the browser to download the Blob object from the URL as a file.

The user can then click the link, and they will be presented with the standard save dialog from the web browser, allowing them to save the generated file wherever they wish.

write to a file from Node.js. If you're working in a Node.js environment, all of the tools for managing files are available in the built-in fs library.

Reading or writing files takes time and can halt execution. Previously, it was best to use callbacks to perform file operations once a file has been successfully read or written to. Now, however, Promises provide a standardized approach for asynchronous tasks.


writing to page

top
examples
code:
                <div class="spec">

                </div>
                <script>
                    document.firstline = "Welcome to this page"
                    document.open()
                    document.write(document.firstline)
                    document.open()
                </script>
            


write to a file from the browser with JavaScript

top
examples
code:
                <div class="spec">
                <a id="downloadLink" href="#" download="myFile.txt">Download</a>
                </div>
                <script>
                    // A global variable should be defined to hold the URL for the file to be downloaded
                    var textFileUrl = null;
                    // Function for generating a text file URL containing given text
                    function generateTextFileUrl(txt) {
                        let fileData = new Blob([txt], {type: 'text/plain'});
                        if (textFileUrl !== null) {
                            window.URL.revokeObjectURL(textFile);
                        }
                        textFileUrl = window.URL.createObjectURL(fileData);
                        // Returns a reference to the global variable holding the URL
                        return textFileUrl;
                    };
                    window.addEventListener("load", function(){
                        document.getElementById('downloadLink').href = generateTextFileUrl('Hello world!');
                    });     
                </script>
            


save text to a file in JavaScript

top
examples

Save the text to a file

code:
            <div class="spec">
                <div id="container">
                    <h4>Save the text to a file</h4>
                    <textarea placeholder="Type your text here..." id="text"></textarea>
                    <input id="filename" placeholder="Specify a filename..." />
                    <button id="download">download file</button>
                </div>
            </div>
            <style>
            h4 {color: #0773d7; font-size: 1.22vw;  width: 100%; margin-top: -1vw; margin-bottom: 3vw; text-align: center; 
                text-transform: uppercase;}
            #text {display: block; width: 90%; background-color: transparent;  color: #021652; border: 0.2vw solid #3ba9f4; 
                border-radius: 0.2vw; resize: none; margin-bottom: 1vw; height: 20vw; padding: 0.1vw; font-size: 1vw;}
            #filename {width: calc(100% - 20vw); border: 0.2vw solid #3ba9f4; border-radius: 0.2vw; background-color: 
                transparent; color: #052a53; padding: 0 0.5vw; height: 3vw; line-height: 1; font-size: 1vw; margin-right: 1vw;}
            #download {background-color: #3ba9f4; color: #fff;font-size: 1vw; height: 3vw; border: none;border-radius: 0.2vw; 
                width: 10vw; cursor: pointer;}
            </style>
            <script>
                function downloadFile(filename, content) {
                    const element = document.createElement('a');
                    const blob = new Blob([content], { type: 'plain/text' });
                    const fileUrl = URL.createObjectURL(blob);
                    element.setAttribute('href', fileUrl); //file location
                    element.setAttribute('download', filename); // file name
                    element.style.display = 'none';
                    document.body.appendChild(element);
                    element.click();
                    document.body.removeChild(element);
                };
                window.onload = () => {
                    document.getElementById('download').addEventListener('click', e => {
                        const filename = document.getElementById('filename').value;
                        const content = document.getElementById('text').value;
                        if (filename && content) {
                            downloadFile(filename, content);
                        }
                    });
                };
            </script>
            


checkbox inputs to file

top
examples
notes:
initials:
check general health.
check fluid.
code:
                <div class="spec">
                    <form name="addtext">
                        notes:<input type="text" name="notes" /><br /> 
                        initials:<input type="text" name="initials" /><br />
                        <input type="checkbox" name="check-health" value="Check General Health" />
                        <b>check general health.</b><br />
                        <input type="checkbox" name="check-fluid" value="Check Fluid" />
                        <b>check fluid.</b><br />
                        <input type="text" name="name" value="" placeholder="File Name" />
                        <input type="submit" value="save as txt" />
                    </form>
                </div>
                <style>
                    form{width: 28vw; height: 20vh;}
                </style>
                <script>
                    document.addEventListener("DOMContentLoaded", function() {
                        const form = document.querySelector('form[name="addtext"]');
                        form.addEventListener("submit", function(event) {
                            event.preventDefault();
                            const notes = form.querySelector('input[name="notes"]').value;
                            const initials = form.querySelector('input[name="initials"]').value;
                            const checkFluid = form.querySelector('input[name="check-fluid"]').checked;
                            const checkHealth = form.querySelector('input[name="check-health"]').checked;
                            const filename = form.querySelector('input[name="name"]').value + ".txt";
        
                            /* Compose text file content */
                            const text = `
                                notes:${notes}
                                initials:${initials}
                                check health (checkbox):${checkHealth}
                                check fluid (checkbox):${checkFluid}
                            `;
        
                            /* Create temporary link element and trigger file download  */
                            const link = document.createElement("a");
                            const href = "data:text/plain;charset=utf-8," + encodeURIComponent(text);
                            link.setAttribute("href", href);
                            link.setAttribute("download", filename);
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                        });
                    });
                </script>
            


save form data to file

top
examples
code:
                <div class="vorm">
                    <div><input type="text" id="txtName" placeholder="Enter your name" /></div>
                    <div><input type="text" id="txtAge" placeholder="Enter your age" /></div>
                    <div><input type="text" id="txtEmail" placeholder="Enter your email address" /></div>
                    <div>
                        <select id="selCountry">
                            <option selected value="">Choose the country</option>
                            <option value="India">India</option>
                            <option value="Japan">Japan</option>
                            <option value="USA">USA</option>
                            <option value="USA">China</option>
                            <option value="USA">South Korea</option>
                            <option value="USA">Vietnam</option>
                            <option value="USA">Belgium</option>
                            <option value="USA">UK</option>
                        </select>
                    </div>
                    <div><textarea id="msg" name="msg" placeholder="Write some message ..." 
                    style="height:5vw;"></textarea></div>
                    <div><input type="button" id="bt" value="Save data to file" onclick="saveFile()" />
                    </div>
                </div>
                <style>
                    .vorm{margin-left: 3vw; overflow: hidden; width: 40vw; height: 25vw;float: left; 
                        background-color:skyblue; border: none;}
                    input[type=text]{background-color:lightgreen; width:100%; padding:1vw;border:none; }
                    select, textarea{ text-align: left; padding: 1vw; width: 100%; border: 1px solid #ccc; 
                        border-radius: 0.5vw; background-color:lightgreen;}
                    input[type=button]{ width: auto; float: left; cursor: pointer; padding: 0.7vw; 
                        background-color: burlywood;}
                </style>
                <script>
                    let openFile_A = () =>{
                        const sFileName = 'formData.txt';
                        
                    }
                    let saveFile_A = () => {
                        // Get the data from each element on the form.
                        const name = document.getElementById('txtName');
                        const age = document.getElementById('txtAge');
                        const email = document.getElementById('txtEmail');
                        const country = document.getElementById('selCountry');
                        const msg = document.getElementById('msg');
                        
                        // This variable stores all the data.
                        let data = 
                            '\r Name: ' + name.value + ' \r\n ' + 
                            'Age: ' +age.value + ' \r\n ' + 
                            'Email: ' + email.value + ' \r\n ' + 
                            'Country: ' + country.value + ' \r\n ' + 
                            'Message: ' + msg.value;
                        
                        // Convert the text to BLOB.
                        const textToBLOB = new Blob([data], { type: 'text/plain' });
                        const sFileName = 'formData.txt';	   // The file to save the data.
        
                        let newLink = document.createElement("a");
                        newLink.download = sFileName;
        
                        if (window.webkitURL != null) {
                            newLink.href = window.webkitURL.createObjectURL(textToBLOB);
                        }
                        else {
                            newLink.href = window.URL.createObjectURL(textToBLOB);
                            newLink.style.display = "none";
                            document.body.appendChild(newLink);
                        }
        
                        newLink.click(); 
                    }
                </script>
            


write form data to file

top
examples

Enter the file name:

Enter your name:

Option 1 Option 2
code:
            <form class="vorm" name="myform" method="post" action="#">
                <p class="spec">Enter the file name:<input type="text" id="docname" 
                value="test.txt" /></p>
                <p class="spec">Enter your name: <input type="text" id="name" 
                placeholder="Your Name" /></p>
                <div style="display:unblock">
                    Option 1 <input type="radio" value="Option 1" onclick="getElementById('problem').
                    value=this.value; getElementById('problem').show()" style="display:inline" />
                    Option 2 <input type="radio" value="Option 2" onclick="getElementById('problem').
                    value=this.value;" style="display:inline" />
                    <input type="text" id="problem" />
                </div>
                <textarea rows=3 cols=50 id="text" placeholder="please type in this box your message"> 
                </textarea>
                <input id="download_btn" type="submit" class="btn" style="width: 12.5vw" 
                onClick="download();" />
            </form>
                <script>
                    function download() {
                        var filename = window.document.myform.docname.value;
                        var name =  window.document.myform.name.value;
                        var text =  window.document.myform.text.value;
                        var problem =  window.document.myform.problem.value;
                        
                        var pom = document.createElement('a');
                        pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 
                            "Your Name: " + encodeURIComponent(name) + "\n\n" +
                            "Problem: " + encodeURIComponent(problem) + "\n\n" +
                            encodeURIComponent(text)); 
                        
                        pom.setAttribute('download', filename);
                        pom.style.display = 'none';
                        document.body.appendChild(pom);
                        pom.click();
                        document.body.removeChild(pom);
                        }
                </script>
            


write inputs to file

top
examples
code:
                <form onsubmit="download(this['name'].value, this['text'].value)">
                    <input type="text" name="name" value="test.txt">
                    <textarea rows=3 cols=50 name="text" placeholder="Please type in this box, then press 'download'"></textarea>
                    <input type="submit" value="Download">
                </form>
                <script>
                    function download(filename, text) {
                        var pom = document.createElement('a');
                        pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
                        pom.setAttribute('download', filename);
                        pom.style.display = 'none';
                        document.body.appendChild(pom);
                        pom.click();
                        document.body.removeChild(pom);
                    }
                </script>
            


show position information

top
examples
code:
                <div id="result"></div>
                <button type="button" onclick="showPosition();" style="margin-left:5vw;">Show Position</button>
                <script>
                    function showPosition() {
                        if(navigator.geolocation) {
                            navigator.geolocation.getCurrentPosition(function(position) {
                                var positionInfo = "Your current position is " + "<br>" + "Latitude: " 
                                + position.coords.latitude + ", " + "<br>" + "Longitude: " + position.coords.longitude;
                                document.getElementById("result").innerHTML = positionInfo;
                            });
                        } else {
                            alert("Sorry, your browser does not support HTML5 geolocation.");
                        }
                    }
                </script>
            


submit input data to text file

top
examples
code:
                <div style="margin-left:5vw; width: 50%;">
                    <div><input type="text" id="txtName" placeholder="Enter your name" /></div>
                    <div><input type="text" id="txtAge" placeholder="Enter your age" /></div>
                    <div><input type="text" id="txtEmail" placeholder="Enter your email address" /></div>
                    <div>
                        <select id="selCountry">
                            <option selected value="">-- Choose the country --</option>
                            <option value="China">China</option>
                            <option value="Dubai">Dubai</option>
                            <option value="Finland">Finland</option>
                            <option value="India">India</option>
                            <option value="Japan">Japan</option>
                            <option value="USA">USA</option>
                        </select>
                    </div>
                    <div><textarea id="msg" name="msg" placeholder="Write some message ..." 
                    style="height:100px"></textarea></div>
                    <div><input type="button" id="bt" value="Save data to file" onclick="saveFile()" /></div>
                </div> 
                <script>
                    let openFile = () =>{const sFileName = 'formData.txt';}
                    let saveFile = () => { 
                        // Get the data from each element on the form.
                        const name = document.getElementById('txtName');
                        const age = document.getElementById('txtAge');
                        const email = document.getElementById('txtEmail');
                        const country = document.getElementById('selCountry');
                        const msg = document.getElementById('msg');
                        // This variable stores all the data.
                        let data = 
                            '\r Name: ' + name.value + ' \r\n ' + 
                            'Age: ' + age.value + ' \r\n ' + 
                            'Email: ' + email.value + ' \r\n ' + 
                            'Country: ' + country.value + ' \r\n ' + 
                            'Message: ' + msg.value;
                        // Convert the text to BLOB.
                        const textToBLOB = new Blob([data], { type: 'text/plain' });
                        const sFileName = 'formData.txt';	   // The file to save the data.
                        let newLink = document.createElement("a");
                        newLink.download = sFileName;
                        if (window.webkitURL != null) {
                            newLink.href = window.webkitURL.createObjectURL(textToBLOB);
                        }
                        else {
                            newLink.href = window.URL.createObjectURL(textToBLOB);
                            newLink.style.display = "none";
                            document.body.appendChild(newLink);
                        }
                        newLink.click(); 
                    }
                </script>