Saving files in javascript

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 FileSaver – saveAs(new File([«CONTENT»], «demo.txt», ));
  2. Create a blob object and offer a “save as”.
    • var a = document.createElement(«a»);
    • a.href = window.URL.createObjectURL(new Blob([«CONTENT»], ));
    • 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»], ));
    • 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»], ));
    • 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!

Читайте также:  №3-3

TLDR – QUICK SLIDES

How To Save Files In Javascript

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

// (A) CREATE BLOB OBJECT var myBlob = new Blob(["CONTENT"], ); // (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

  

THE PHP

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

  

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

// (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.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

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.

  • Javascript Blob – MDN
  • MIME Types – SitePoint
  • Create Object URL and Revoke Object URL – MDN
  • Form Data – MDN
  • Fetch API – MDN
  • Write Files In NodeJS – Code Boxx

TUTORIAL VIDEO

INFOGRAPHIC CHEAT SHEET

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!

Источник

How to Save Files in JavaScript

Save As

In the web world, saving a file or “Save As” means downloading a file to the client’s machine. There isn’t a built-in method in JavaScript that allows us to do so. What we typically do (if we have a static file link) is add an anchor element in HTML and use the download attribute to make it downloadable. Something like this:

a href="/images/myFile.txt" download>

The problem is that we don’t always want the user to download when clicking on a link because we could have a bunch of logic before downloading or some dynamic data created without a static link. Let’s go through a few simple steps to create a saveAs function for downloading one or multiple files in JavaScript!

Unless we have static files available publicly on the server, we need to create content using a Blob , a file-like object in JavaScript.

Let’s create a function that will take some data as a parameter and return a new Blob text:

function createBlob(data)   return new Blob([data],  type: "text/plain" >); >

Of course, a Blob object has a lot more than just a plain text type. You can learn more in the official documentation.

Let’s look at two approaches for saving/downloading a file in JavaScript:

1. Use an Anchor element

We can dynamically create an anchor element in JavaScript using createElement and then programmatically invoke the click event. Here is a basic example:

const a = document.createElement("a"); a.click();

But to download a file, we need to pass it download and href attributes. The download will hold the file name and extension and the href will require a URL. Let’s create a function and put all the implementation together:

If we are using a static file with a relative path, all we need to do is this:

function saveAs()   const a = document.createElement("a");  a.href = '/files/myFile.txt';  a.download = "myFile.txt";  a.click(); >

Download only works for same-origin URLs. Meaning, href can’t be a path different than your websites’ otherwise the behavior will change and it will redirect instead of downloading.

If the content is generated dynamically, we’ll need to create a blob and convert it to an object URL to make it downloadable. Also, we need to release the object at the very end when no longer needed:

function saveAs()   const a = document.createElement("a");  const file = createBlob("Hello Blob!!");  const url = window.URL.createObjectURL(file);  a.href = url;  a.download = "myFile.txt";  a.click();  URL.revokeObjectURL(); >

Let’s improve the function to make it re-usable and have it support both options:

function saveAs(content, fileName)   const a = document.createElement("a");  const isBlob = content.toString().indexOf("Blob") > -1;  let url = content;  if (isBlob)   url = window.URL.createObjectURL(content);  >  a.href = url;  a.download = fileName;  a.click();  if (isBlob)   window.URL.revokeObjectURL(url);  > > // Consume the function as follows: const file = createBlob("Hello, file!"); saveAs(file, "myFile.txt");

2. Use file-saver library

FileSaver.js is a great solution to saving files on the client-side without having to write our own custom code.

First, we need to install the library:

const FileSaver = require('file-saver'); // Save Blob file const file = createBlob('Hello, file!'); FileSaver.saveAs(file, "myFile.txt"); // Save URL FileSaver.saveAs("https://httpbin.org/image", "image.jpg");

Zip and download multiple files

In certain cases, we need to download multiple files in one hit. Although this can be achieved by looping through the files and triggering the saveAs function, the user experience isn’t great and we’ll end up with so many files added to the download folder.

An alternative solution is to use JSZip, a library for creating, reading, and editing .zip files.

First, we need to install the library:

Then, we’ll create an async function that does the following logic:

const file1 = createBlob("Hello Blob 1!"); const file2 = createBlob("Hello Blob 2!");
const zip = new JSZip(); zip.file("file1.txt", file1); zip.file("file2.txt", file2);
  1. Generate the zip folder and as soon as it’s ready, we can call the saveAs function we did earlier:
const content = await zip.generateAsync( type: "blob" >); saveAs(content, "folder.zip");

Here is the full function:

async function zipFiles()   const zip = new JSZip();  const file1 = createBlob("Hello, file 1!");  const file2 = createBlob("Hello, file 2!");  zip.file("file1.txt", file1);  zip.file("file2.txt", file2);  const content = await zip.generateAsync( type: "blob" >);  saveAs(content, "folder.zip"); >

I hope you enjoyed learning from this article and if you have any questions, please leave a comment below.

Источник

Оцените статью