5 Ways To Create & Save Files In Javascript (Simple Examples)

Welcome to a tutorial on how to create and save files in Javascript. Well, this will be kind of a complicated process for beginners. To keep things simple – Saving files on the server-side NodeJS is a breeze, but it is tricky to directly save files on the client side because of security restrictions. That said, there are many methods we can use.

The possible ways to create and save files in Javascript are:

  1. Use a library called FileSaversaveAs(new File(["CONTENT"], "demo.txt", {type: "text/plain;charset=utf-8"}));
  2. Create a blob object and offer a “save as”.
    • var a = document.createElement("a");
    • a.href = window.URL.createObjectURL(new Blob(["CONTENT"], {type: "text/plain"}));
    • a.download = "demo.txt";
    • a.click();
  3. Upload the data, save it on the server.
    • var data = new FormData();
    • data.append("upfile", new Blob(["CONTENT"], {type: "text/plain"}));
    • fetch("SERVER.SCRIPT", { method: "POST", body: data });
  4. Create a writable file stream.
    • const fileHandle = await window.showSaveFilePicker();
    • const fileStream = await fileHandle.createWritable();
    • await fileStream.write(new Blob(["CONTENT"], {type: "text/plain"}));
    • await fileStream.close();
  5. In NodeJS, simply use the file system module – require("fs").writeFile("demo.txt", "Foo bar!");

That covers the basics, but let us walk through detailed examples in this tutorial – Read on!

 

 

TABLE OF CONTENTS

 

 

SAVE FILES IN JAVASCRIPT

All right, let us now get into the various ways to save files in Javascript.

 

METHOD 1) USE FILE SAVER

1-filesaver.js
<!-- (A) LOAD FILE SAVER -->
<!-- https://cdnjs.com/libraries/FileSaver.js -->
<!-- https://github.com/eligrey/FileSaver.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
 
<script>
// (B) "SAVE AS"
var myFile = new File(["CONTENT"], "demo.txt", {type: "text/plain;charset=utf-8"});
saveAs(myFile);
</script>

Thank goodness, someone did all the hard work. This is one of the easiest and “safest” cross-browser ways to save a file –

  1. Simply load FileSaver.js from the CDN.
  2. Create a new File() object and pop it into saveAs().

 

 

METHOD 2) CREATE FILE FROM BLOB & FORCE DOWNLOAD

2-blob-download.html
// (A) CREATE BLOB OBJECT
var myBlob = new Blob(["CONTENT"], {type: "text/plain"});

// (B) CREATE DOWNLOAD LINK
var url = window.URL.createObjectURL(myBlob);
var anchor = document.createElement("a");
anchor.href = url;
anchor.download = "demo.txt";
 
// (C) "FORCE DOWNLOAD"
// NOTE: MAY NOT ALWAYS WORK DUE TO BROWSER SECURITY
// BETTER TO LET USERS CLICK ON THEIR OWN
anchor.click();
window.URL.revokeObjectURL(url);
document.removeChild(anchor);

Due to security restrictions, client-side Javascript cannot directly access the file system. That is, no direct writing and loading of files on the user’s computer. But this is the roundabout way of doing things – Create a BLOB (binary) object to contain all the data, then set a download link to it.

 

METHOD 3) UPLOAD BLOB TO SERVER

THE JAVASCRIPT

3a-blob-upload.html
<script>
function blobajax () {
  // (A) CREATE BLOB OBJECT
  var myBlob = new Blob(["CONTENT"], {type: "text/plain"});

  // (B) FORM DATA
  var data = new FormData();
  data.append("upfile", myBlob);

  // (C) AJAX UPLOAD TO SERVER
  fetch("3b-upload.php", { method: "POST", body: data })
  .then(res => res.text())
  .then(txt => console.log(txt));
}
</script>
<input type="button" value="Go" onclick="blobajax()">

 

THE PHP

3b-blob-upload.php
<?php
echo move_uploaded_file(
  $_FILES["upfile"]["tmp_name"], 
  "demo.txt"
) ? "OK" : "ERROR UPLOADING";

This is an alternative to the above BLOB download – We upload the BLOB and save it on the server instead.

 

 

METHOD 4) WRITABLE FILE STREAM

4-file-stream.html
<script>
async function saveFile() {
  // (A) CREATE BLOB OBJECT
  var myBlob = new Blob(["CONTENT"], {type: "text/plain"});
 
  // (B) FILE HANDLER & FILE STREAM
  const fileHandle = await window.showSaveFilePicker({
    types: [{
      description: "Text file",
      accept: {"text/plain": [".txt"]}
    }]
  });
  const fileStream = await fileHandle.createWritable();
 
  // (C) WRITE FILE
  await fileStream.write(myBlob);
  await fileStream.close();
}
</script>
<input type="button" value="Save File" onclick="saveFile()">

Yes, the old grandmother’s age of the Internet is over. We can create a file handler and file stream on the user’s computer, use it to save a file. But this still opens a “save file as” dialog box, we cannot directly save without the user’s permission.

P.S. This will only work on Chrome, Edge, and Opera at the time of writing.

 

METHOD 5) WRITE TO FILE IN NODEJS

5-node.js
// (A) LOAD FILE SYSTEM MODULE
// https://nodejs.org/api/fs.html
const fs = require("fs");

// (B) WRITE TO FILE
fs.writeFile("demo.txt", "CONTENT", "utf8", (error, data) => {
  console.log("Write complete");
  console.log(error);
  console.log(data);
});

/* (C) READ FROM FILE
fs.readFile("demo.txt", "utf8", (error, data) => {
  console.log("Read complete");
  console.log(error);
  console.log(data);
});
*/

Yes, it’s that stupidly simple. Just load the file system module var fs = require("fs"), and use the writeFile() function. To load files, we use the corresponding readFile() function.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here to download. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA BITS & LINKS

That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.

 

COMPATIBILITY CHECKS

Not all browsers support the BLOB data type nor all the file writing features. So it is best to do some checks before you enable your ninja features – I will recommend using Modernizr to detect if the browser supports certain features.

 

LINKS & REFERENCES

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEAT SHEET

How To Save Files In Javascript (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

3 thoughts on “5 Ways To Create & Save Files In Javascript (Simple Examples)”

  1. great news you appear at the top of my google search for “save file locally javascript”.

    “about page” is great love it. What a nice deep comment I agree with you “to help yourself help others”.

    reluctantly though, I like to point just 2 issues in your local save section. that was the only one I prefer implementing.

    1. to get events like click() event you need to add the “anchor” element to the document.body and in a finally{} block remove the element from the document.
    2. if you create an object URL you need to release it once done. good house keeping ha? if you are working on a large app could be resource hungry and it can bite back.
    use URL.revokeObjectURL() in a finally {} block

    Kind regards
    Tony

    1. Thanks for sharing. That may help, but it does not quite matter if the anchor tag is attached to the body or not. Some browsers and anti-virus simply don’t allow Javascript to click on links.

Comments are closed.