How do i save a text file in javascript?

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Pre-requisite: How to import a library in JavaScript. Read from here: https://www.geeksforgeeks.org/javascript-importing-and-exporting-modules/ .

    There is a built-in Module or in-built library in NodeJs which handles all the writing operations called fs (File-System). It is basically a JavaScript program (fs.js) where function for writing operations is written. Import fs-module in the program and use functions to write text to files in the system. The following function will create a new file with a given name if there isn’t one, else it will rewrite the file erasing all the previous data in it.

    Used Function: The writeFile() functions is used for writing operation.

    Syntax:

    writeFile( Path, Data, Callback)

    Parameters: This method accepts three parameters as mentioned above and described below:

    • Path: It takes in relative path from the program to the text File. If the file is to be created in the same folder as that of the program, then give the name of the file only. If file not exists then new file will be created automatically.
    • Data: This argument takes in data which need to write in the file.
    • Callback Function: It is the callback function which further has an argument (err). If the operation fails to write the data, err shows the fault.

    Example:

    <script>

    const fs = require('fs')

    let data = "Learning how to write in a file."

    fs.writeFile('Output.txt', data, (err) => {

        if (err) throw err;

    })

    </script>

    Output:

    Learning how to write in a file.

    Note: Above script can be run using NodeJs interpreter in terminal.

    How do i save a text file in javascript?

    For whatever reasons, you might want to generate text file with javascript dynamically and let user download it without involvement of server side script. In this tutorial, I’ll show you how to do that in a couple minutes!

    To create a text file from javascript, we’ll need to use Blob object. Blob (A Binary Large OBject) is a collection of binary data stored as a single entity. So, we’re going to create a Blob object that contains our text content. Then we’ll convert a blob into a text file which web browser will then popup the download dialog box for the users. This might sounds difficult but if you know the right tools, it’s just a couple lines of code. This solution is also cross browsers support (Well, I mean modern browsers as this won’t work with IE9 and below)

    Assume that you already have your button binded with click event. (Code below uses jQuery)

    $("#save-btn").click(function() { 
       
    });

    We’ll use Blob() constructor and pass our text string as first parameter. Noted that we have to put it in array form. The second parameter, we’ll define our blob type as plain text with utf-8 encoding.

    $("#save-btn").click(function() { 
       var blob = new Blob(["This is my first text."], {type: "text/plain;charset=utf-8"});
    });

    Now we have our blob object, next we’ll need to convert it to text file. There is a very nice javascript plugin calls Filesaver.js take blob object as input and let you save files on web browser. After included the filesaver.js to your page, use saveAs() to trigger the download popup dialog.

    $("#save-btn").click(function() { 
       var blob = new Blob(["This is my first text."], {type: "text/plain;charset=utf-8"});
       saveAs(blob, "testfile1.txt");
    });

    Please see video tutorial below for step by step instruction.

    Lastly, don’t forget to checkout our Youtube Channel for other interesting tutorials or leave the comment below if you have any questions or feedback. Thanks!

    Red Stapler Channel: https://www.youtube.com/c/RedStapler_channel

    How do i save a text file in javascript?

    Another one of those 'born of an issue I stumbled across' sort of situations, I came across the need to save some data entered into a form (some configuration details into a textarea to be specific).

    Sure, there are lots of means available to save something to the local machine of a user, but they tend to involve either less-than-ideal solutions such as a browser's local storage, a cookie, or even using the HTML canvas blob.

    The need for simple solutions

    There is a great article (if not a little out of date by now) by Eli Grey on saving generated files on the client side that also discusses his excellent utility FileSaver.js, which utilises the very same canvas blob functions mentioned above.

    However, for me, it seemed a little overblown to bring in another utility dependency to perform a really simple task of creating a small text file and stashing it on the client's machine.

    A vanilla JS solution to client-side file saving

    So here we are, a really simple way to create and save a file on the client side, from the browser, based on some information saved into a textarea.

    First, the HTML...

    <fieldset>
      <legend>Enter some config details</legend>
      <textarea></textarea>
      <button id="btnSave">save config</button>
    </fieldset>
    

    Which renders the following no-frills elements in the browser (styling not shown for simplicity):

    How do i save a text file in javascript?

    Now, for the JavaScript:

    const downloadToFile = (content, filename, contentType) => {
      const a = document.createElement('a');
      const file = new Blob([content], {type: contentType});
      
      a.href= URL.createObjectURL(file);
      a.download = filename;
      a.click();
    
    	URL.revokeObjectURL(a.href);
    };
    
    document.querySelector('#btnSave').addEventListener('click', () => {
      const textArea = document.querySelector('textarea');
      
      downloadToFile(textArea.value, 'my-new-file.txt', 'text/plain');
    });
    

    What we've got going on here, is a plain, browser-native querySelector call that grabs our button with the id btnSave, attaches an event listener that fires on click — nothing too fancy here.

    Where the magic (well, really simple magic) is in the 'downloadToFile' method above. We create a new anchor element and a new Blob object using the content and contentType arguments we passed in.

    Next, we set the href element to the result of the URL.createObjectURL() method that creates a DOMString containing a URL that represents the file object we just made.

    Finally, we trigger our new anchor element's click event, which kicks off the download process in the browser, before cleaning things up using the URL.revokeObjectURL() method.

    See it in action

    You can view the code in action in my CodePen, or below in a handy iFrame.

    Wrapping things up

    And that's it. Nice and simple, gets the job done. Sometimes, the most straightforward solution is the best one if you need something lightweight that just works.

    You might also like these articles that use plain old JS and CSS:

    • Funky text backgrounds with background-clip CSS
    • Creating unique, merged arrays using JavaScript's Set (and more)
    • Configure Parcel JS and Babel to use JavaScript proposal class properties
    • How to use arrow functions in JavaScript ES6

    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 text in JavaScript?

    The possible ways to create and save files in Javascript are: Use a library called FileSaver – saveAs(new File(["CONTENT"], "demo. txt", {type: "text/plain;charset=utf-8"})); Create a blob object and offer a “save as”.

    Can we create file in JavaScript?

    Did you know you can create files using JavaScript right inside your browser and have users download them? You can create files with a proper name and mime type and it only takes a few lines of code.

    What does save () do in JavaScript?

    save() method of the Canvas 2D API saves the entire state of the canvas by pushing the current state onto a stack.