How to save data in notepad using javascript

By Atul Rai | Last Updated: March 2, 2019 Previous       Next

As we know that JavaScript is one of the most popular high-level, interpreted programming language in the world. Now it is capable to do almost everything that we are doing in other programming languages. To know more about check out the StackOverflow 2018 survey.

What we’ll build

In this tutorial, we will create and save the data into a text file. To do that we’ll write:

  1. A JavaScript function that fire on the button click event.
  2. Create a Blob constructor, pass the data in it to be to save and mention the type of data.
  3. And finally, call the saveAs[Blob object, "your-file-name.text"] function of FileSaver.js library.

Note: To create and save data into a text file, I have used a third party FileSaver.js library.

Let’s jump into the actual juicy part of the code.

1. Saving static data

1.1 Create a function that executes on button click event.

function saveStaticDataToFile[] {
}

1.2 Instantiate the Blob object and pass a text string as the first parameter and blob type as the second parameter.

var blob = new Blob[["Welcome to Websparrow.org."],
                { type: "text/plain;charset=utf-8" }];

1.3 Now call the saveAs function which takes blob object as input and let you save files on web browser.

saveAs[blob, "static.txt"];

Check out the complete example.




    
    
    How to Create and Save text file in JavaScript
    

    

        function saveStaticDataToFile[] {
            var blob = new Blob[["Welcome to Websparrow.org."],
                { type: "text/plain;charset=utf-8" }];
            saveAs[blob, "static.txt"];
        }
		
    



    Click to Save


2. Saving dynamic data

To save user input data into a text file, first, we need to store user’s data into a variable and pass that variable as Blob first parameter. Check out the complete code example.




    
    
    How to Create and Save text file in JavaScript
    
    

		function saveDynamicDataToFile[] {

            var userInput = document.getElementById["myText"].value;
			
            var blob = new Blob[[userInput], { type: "text/plain;charset=utf-8" }];
            saveAs[blob, "dynamic.txt"];
        }

    



    
 We love to share our experiments, ideas, and knowledge with everyone by writing articles on the latest technology trends.
    

    Click to Save
	

Remember: Don’t forget to import FileSaver.js library in your document [html/jsp/etc].

Done. Thank You 🙂

References

  1. FileSaver.jsp library
  2. Most Popular Technologies
  3. Blob- Web API | MDN

I am sharing a simple example here today that explains how easily you can save your form data in a text file or in a .txt file using JavaScript.

A web form usually has many different elements, mostly input fields. You can extract data from these elements and save it in a database like SQL Server, or simply convert it into a JSON file. You can even save your form data in a text file.

Let’s see the example first.



    Save form Data in a Text File using JavaScript
    
        * {
            box-sizing: border-box;
        }
    	div {
            padding: 10px;
            background-color: #f6f6f6;
            overflow: hidden;
        }
    	input[type=text], textarea, select {
            width: 100%;
            padding: 12px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        input[type=button]{ 
            width: auto;
            float: right;
            cursor: pointer;
            padding: 7px;
        }
    


    
-- Choose the country -- India Japan USA
let saveFile = [] => { 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']; 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; const textToBLOB = new Blob[[data], { type: 'text/plain' }]; const sFileName = 'formData.txt'; 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[]; }

Try it

Please do not get overwhelmed by the size of the program. The code inside the tag is important.

I have designed a simple form using CSS and few HTML elements along with a dropdown list. I idea behind using so many elements is to show you how you can save form data in text file using values extracted from different input elements.

Inside the script, the first thing I am doing is getting all the values from each element.

Later, I am creating a string [using the values], so that I can convert the whole string into a BLOB object.

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;

The \r\n is for new line or line breaks, so that each data can be written in a new line in the text file.

Next, I am creating a Link [the anchor tag] [which is not visible anywhere on the form] and assigning the text file as the link’s download property.

let newLink = document.createElement["a"];
newLink.download = sFileName;

Once I have created the link, I’ll assign the BLOB object as the href [or as the URL] to the newly created Link tag.

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];
}

👉 Now, you can also convert your Form data into PDF using JavaScript.

BLOB stands for Binary Large Object. BLOBs are typically, images and audio files, which are converted into Binary and are later stored in a database. Using the Blob[] constructor, I can convert ordinary texts into Blob objects.

You can see the BLOB value [attached to the link’s URL or tag that we created in our script] in your browser’s console window. For example,

if [window.webkitURL != null] {
    newLink.href = window.webkitURL.createObjectURL[textToBLOB];
    console.log [newLink];    
}

image

The image shows the tag with URL having the blob value. In the console window, copy the URL and paste it in the browser’s address bar. The browser will translate the BLOB and will show the value.

Remember: Every time you click the save button, the script will create a new BLOB from the form data.

The final line of code, simply calls the click event of the tag and the browser downloads the file containing the data in your local hard disc.

newLink.click[];

👉 Not just plain text, you can even convert an image into a PDF using only JavaScript. Check out this post.

That's it. Thanks for reading.

← PreviousNext →


How do I save a text File using JavaScript?

How to Create and Save text file in JavaScript.
A JavaScript function that fire on the button click event..
Create a Blob constructor, pass the data in it to be to save and mention the type of data..
And finally, call the saveAs[Blob object, "your-file-name. text"] function of FileSaver. js library..

How do I save information in JavaScript?

Store Data in the Browser with JavaScript.
setItem[key, value] store key/value pair..
getItem[key] gets the value by key..
removeItem[key] remove the key and value..
clear[] delete everything from the storage..
key[index] get the key from a given position..
length the count of stored items..

How do I save textbox value to .TXT File in HTML using JavaScript?

If you want, you can download the source code of this project [Textarea Text to a File using JavaScript]..
Create a box on the webpage.
... .
Add a heading. ... .
Create a text input box. ... .
Create a box to input the file name. ... .
Create file download button. ... .
Save Text to File with JavaScript..

Does JavaScript work on Notepad?

If you are a beginner and want to go for a simple approach for writing JavaScript programs, use a simple text editor like Notepad++. It is free, open-source, and will work fine for JavaScript development. Notepad++ is a general-purpose editor that supports highlights the syntax of JavaScript and HTML code.

Chủ Đề