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 in server-side NodeJS is a breeze, but it is impossible to directly save files because of security restrictions. That said, we can still offer the file as a download.

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

  1. The easiest way to save a file in client-side Javascript is to use FileSaver.
    • var myFile = new File(["CONTENT"], "demo.txt", {type: "text/plain;charset=utf-8"});
    • saveAs(myFile);
  2. Alternatively, manually create a blob and offer a “save as”.
    • var myBlob = new Blob(["CONTENT"], {type: 'text/plain'});
    • var anchor = document.createElement("a")s
    • anchor.download = "demo.txt";
    • anchor.url = window.URL.createObjectURL(myBlob);
    • anchor.click();
  3. Upload the data, save it on the server instead.
    • var myBlob = new Blob(["CONTENT"], {type: 'text/plain'});
    • var data = new FormData();
    • data.append("upfile", myBlob);
    • var xhr = new XMLHttpRequest();
    • xhr.open("POST", "SERVER.SCRIPT");
    • xhr.send(data);
  4. Save the data to the local storage.
    • var myBlob = new Blob(["CONTENT"], {type: "text/plain"});
    • localStorage.setItem("myBlob", myBlob);
  5. In NodeJS, simply use the file system module.
    • var fs = require('fs');
    • fs.writeFile("DEMO.TXT", "Foo bar!");

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

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes JS Save File Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

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

 

QUICK NOTES

There is nothing to install, so just download and unzip into a folder. If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

SAVE FILES IN JAVASCRIPT

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

 

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 as simple as it gets – Load FileSaver.js from the CDN, create a new File() object and pop it into saveAs().

 

 

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.

 

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
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "3b-upload.php");
  xhr.onload = function () {
    console.log(this.status);
    console.log(this.response);
  };
  xhr.send(data);
}
</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.

 

 

4) SAVE BLOB TO LOCAL STORAGE

4-local.html
<script>
// (A) SAVE BLOB TO LOCALSTORAGE
function save () {
  var myBlob = new Blob(["CONTENT"], {type: "text/plain"});
  localStorage.setItem("myBlob", myBlob);
  console.log(localStorage.myBlob);
  alert("Saved");
}
 
// (B) LOAD BLOB FROM LOCALSTORAGE
function load() {
  var myBlob = localStorage.getItem("myBlob");
  if (myBlob == null) {
    alert("Not found");
  } else {
    alert("Loaded");
    console.log(myBlob);
  }
}
 
// (C) DELETE BLOB FROM LOCALSTORAGE
function del() {
  localStorage.removeItem("myBlob");
  console.log(localStorage.myBlob);
  alert("Cleared");
}
</script>
<input type="button" value="Save to local storage" onclick="save()"/>
<input type="button" value="Load from local storage" onclick="load()"/>
<input type="button" value="Delete from local storage" onclick="del()"/>

Lastly, while we cannot directly access the user’s file system in client-side Javascript, there is something called the localStorage. This is a small “sandbox” area that is actually meant to store smaller pieces of data such as strings and flags.

But yep, we can also use it to store BLOB objects. Just take note that it has limited space and the localStorage will be flushed whenever the user clears the cache/history; Don’t count on it to store any critical files and data.

 

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", "Foo bar!", "utf8", function(error, data){
  console.log("Write complete");
  console.log(error);
  console.log(data);
});

/* (C) READ FROM FILE
fs.readFile("demo.txt", "utf8", function(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.

 

 

USEFUL 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.

 

BLOB IS NOT SUPPORTED ON ANCIENT BROWSERS!

Not all browsers support the BLOB data type nor local storage. So it is best to do some checks before you enable your ninja features – Check out Modernizr, a library that you can use to detect if the browser supports certain features.

 

YOUTUBE TUTORIAL

 

INFOGRAPHIC CHEAT SHEET

How To Save Files In Javascript (click to enlarge)

 

LINKS & REFERENCES

 

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!

Leave a Comment

Your email address will not be published. Required fields are marked *