Convert Figma logo to code with AI

eligrey logoFileSaver.js

An HTML5 saveAs() FileSaver implementation

21,522
4,384
21,522
208

Top Related Projects

StreamSaver writes stream to the filesystem directly asynchronous

Detect the file type of a file, stream, or data

5,494

high speed zlib port to javascript, works in browser & node.js

34,966

📗 SheetJS Spreadsheet Data Toolkit -- New home https://git.sheetjs.com/SheetJS/sheetjs

12,413

Fast and powerful CSV (delimited text) parser that gracefully handles large files and malformed input

9,737

Create, read and edit .zip files with Javascript

Quick Overview

FileSaver.js is a client-side solution for saving files in web applications. It allows developers to trigger file downloads directly from JavaScript, without relying on server-side scripts. This library is particularly useful for generating and saving files on the fly, such as dynamically created text files, images, or other data.

Pros

  • Cross-browser compatibility, supporting most modern browsers
  • Easy to use with a simple API
  • No dependencies, lightweight solution
  • Works with large files and various file types

Cons

  • Limited control over the save location (determined by the browser)
  • May not work in some older browsers or mobile devices
  • Doesn't provide file system access or manipulation capabilities
  • Potential security restrictions in some environments

Code Examples

  1. Saving a text file:
const blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello.txt");
  1. Saving a canvas as an image:
const canvas = document.getElementById("myCanvas");
canvas.toBlob(function(blob) {
    saveAs(blob, "myImage.png");
});
  1. Saving data from an AJAX request:
fetch('https://api.example.com/data')
    .then(response => response.blob())
    .then(blob => saveAs(blob, "data.json"));

Getting Started

  1. Include the FileSaver.js library in your HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
  1. Use the saveAs function in your JavaScript code:
const content = "This is the content of my file.";
const blob = new Blob([content], {type: "text/plain;charset=utf-8"});
saveAs(blob, "myFile.txt");

This will trigger a download of a text file named "myFile.txt" with the specified content.

Competitor Comparisons

StreamSaver writes stream to the filesystem directly asynchronous

Pros of StreamSaver.js

  • Supports saving large files without memory limitations
  • Utilizes streaming technology for efficient data handling
  • Works well with progressive loading and real-time data

Cons of StreamSaver.js

  • Requires more setup and configuration compared to FileSaver.js
  • Limited browser support, mainly works in modern browsers
  • May have compatibility issues with older systems or environments

Code Comparison

StreamSaver.js:

const fileStream = streamSaver.createWriteStream('filename.txt')
const writer = fileStream.getWriter()
writer.write(data)
writer.close()

FileSaver.js:

const blob = new Blob([data], {type: "text/plain;charset=utf-8"})
saveAs(blob, "filename.txt")

Summary

StreamSaver.js is better suited for handling large files and streaming data, but requires more setup and has limited browser support. FileSaver.js is simpler to use and has broader compatibility, but may struggle with very large files due to memory constraints. The choice between the two depends on the specific requirements of your project, such as file size, target browsers, and data handling needs.

Detect the file type of a file, stream, or data

Pros of file-type

  • Detects file types based on content, not just extensions
  • Supports a wide range of file formats
  • Can be used in both Node.js and browser environments

Cons of file-type

  • Focuses on file type detection, not saving files
  • Requires additional code to handle file saving functionality
  • May have a larger footprint due to its comprehensive file type database

Code Comparison

file-type:

import {fileTypeFromBuffer} from 'file-type';

const buffer = new Uint8Array([0xFF, 0xD8, 0xFF]);
const fileType = await fileTypeFromBuffer(buffer);
console.log(fileType); // {ext: 'jpg', mime: 'image/jpeg'}

FileSaver.js:

import { saveAs } from 'file-saver';

const blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");

Summary

FileSaver.js is primarily focused on saving files in the browser, while file-type specializes in detecting file types based on content. FileSaver.js is more lightweight and straightforward for file saving tasks, whereas file-type offers robust file type detection capabilities. The choice between the two depends on the specific requirements of your project, whether you need file saving functionality or file type detection.

5,494

high speed zlib port to javascript, works in browser & node.js

Pros of pako

  • Focuses on data compression and decompression using zlib algorithms
  • Supports both browser and Node.js environments
  • Offers high performance and small file size

Cons of pako

  • Limited to compression/decompression tasks, not file saving
  • Requires additional code to handle file saving functionality
  • May have a steeper learning curve for basic file operations

Code Comparison

FileSaver.js:

import { saveAs } from 'file-saver';

const blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");

pako:

import pako from 'pako';

const compressed = pako.deflate("Hello, world!");
const decompressed = pako.inflate(compressed);
console.log(new TextDecoder().decode(decompressed));

Summary

FileSaver.js is primarily designed for saving files in the browser, making it simple to implement file download functionality. pako, on the other hand, focuses on data compression and decompression using zlib algorithms. While pako offers more versatility in terms of data manipulation and supports both browser and Node.js environments, it requires additional code to handle file saving. FileSaver.js provides a more straightforward solution for basic file saving tasks but lacks compression capabilities.

34,966

📗 SheetJS Spreadsheet Data Toolkit -- New home https://git.sheetjs.com/SheetJS/sheetjs

Pros of SheetJS

  • Comprehensive spreadsheet manipulation library
  • Supports multiple file formats (XLSX, CSV, etc.)
  • Extensive API for complex spreadsheet operations

Cons of SheetJS

  • Larger file size and more complex to use
  • May be overkill for simple file saving tasks
  • Requires more setup and configuration

Code Comparison

FileSaver.js:

import { saveAs } from 'file-saver';

const blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");

SheetJS:

import * as XLSX from 'xlsx';

const ws = XLSX.utils.json_to_sheet([{name: "John", age: 30}]);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
XLSX.writeFile(wb, "output.xlsx");

Summary

FileSaver.js is a lightweight solution focused on saving files in the browser, while SheetJS is a comprehensive library for working with spreadsheets. FileSaver.js is simpler to use for basic file saving tasks, but SheetJS offers more advanced features for spreadsheet manipulation and supports multiple file formats. Choose FileSaver.js for simple file saving needs and SheetJS for complex spreadsheet operations.

12,413

Fast and powerful CSV (delimited text) parser that gracefully handles large files and malformed input

Pros of PapaParse

  • Specialized in parsing CSV and other delimited text files
  • Supports streaming large files and web workers for better performance
  • Offers more advanced parsing options and configurations

Cons of PapaParse

  • Limited to parsing and not focused on file saving functionality
  • May be overkill for simple CSV handling tasks
  • Larger file size compared to FileSaver.js

Code Comparison

PapaParse (parsing CSV):

Papa.parse(file, {
  complete: function(results) {
    console.log(results.data);
  }
});

FileSaver.js (saving file):

var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello.txt");

Summary

PapaParse is a powerful CSV parsing library with advanced features, while FileSaver.js focuses on saving files in the browser. PapaParse is ideal for complex CSV handling, but may be unnecessary for simple tasks. FileSaver.js is more lightweight and specialized in file saving. Choose based on your specific needs: parsing (PapaParse) or saving (FileSaver.js).

9,737

Create, read and edit .zip files with Javascript

Pros of JSZip

  • Provides comprehensive ZIP file creation and manipulation functionality
  • Supports various compression methods and file formats within ZIP archives
  • Offers both synchronous and asynchronous operations for flexibility

Cons of JSZip

  • Larger file size and potentially higher memory usage due to more features
  • May have a steeper learning curve for simple file-saving operations
  • Requires additional setup for basic file downloads compared to FileSaver.js

Code Comparison

FileSaver.js:

import { saveAs } from 'file-saver';

const blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello.txt");

JSZip:

import JSZip from 'jszip';

const zip = new JSZip();
zip.file("hello.txt", "Hello, world!");
zip.generateAsync({type:"blob"}).then(function(content) {
    saveAs(content, "example.zip");
});

Both libraries can be used for file saving, but JSZip focuses on creating and manipulating ZIP archives, while FileSaver.js is primarily for saving individual files. JSZip requires more code for simple file saves but offers extensive ZIP-related functionality. FileSaver.js provides a more straightforward approach for basic file downloads but lacks advanced compression and archive features.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

If you need to save really large files bigger than the blob's size limitation or don't have enough RAM, then have a look at the more advanced StreamSaver.js that can save data directly to the hard drive asynchronously with the power of the new streams API. That will have support for progress, cancelation and knowing when it's done writing

FileSaver.js

FileSaver.js is the solution to saving files on the client-side, and is perfect for web apps that generates files on the client, However if the file is coming from the server we recommend you to first try to use Content-Disposition attachment response header as it has more cross-browser compatiblity.

Looking for canvas.toBlob() for saving canvases? Check out canvas-toBlob.js for a cross-browser implementation.

Supported Browsers

BrowserConstructs asFilenamesMax Blob SizeDependencies
Firefox 20+BlobYes800 MiBNone
Firefox < 20data: URINon/aBlob.js
ChromeBlobYes2GBNone
Chrome for AndroidBlobYesRAM/5None
EdgeBlobYes?None
IE 10+BlobYes600 MiBNone
Opera 15+BlobYes500 MiBNone
Opera < 15data: URINon/aBlob.js
Safari 6.1+*BlobNo?None
Safari < 6data: URINon/aBlob.js
Safari 10.1+  Blob        Yes        n/a          None

Feature detection is possible:

try {
    var isFileSaverSupported = !!new Blob;
} catch (e) {}

IE < 10

It is possible to save text files in IE < 10 without Flash-based polyfills. See ChenWenBrian and koffsyrup's saveTextAs() for more details.

Safari 6.1+

Blobs may be opened instead of saved sometimes—you may have to direct your Safari users to manually press ⌘+S to save the file after it is opened. Using the application/octet-stream MIME type to force downloads can cause issues in Safari.

iOS

saveAs must be run within a user interaction event such as onTouchDown or onClick; setTimeout will prevent saveAs from triggering. Due to restrictions in iOS saveAs opens in a new window instead of downloading, if you want this fixed please tell Apple how this WebKit bug is affecting you.

Syntax

Import saveAs() from file-saver

import { saveAs } from 'file-saver';
FileSaver saveAs(Blob/File/Url, optional DOMString filename, optional Object { autoBom })

Pass { autoBom: true } if you want FileSaver.js to automatically provide Unicode text encoding hints (see: byte order mark). Note that this is only done if your blob type has charset=utf-8 set.

Examples

Saving text using require()

var FileSaver = require('file-saver');
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "hello world.txt");

Saving text

var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "hello world.txt");

Saving URLs

FileSaver.saveAs("https://httpbin.org/image", "image.jpg");

Using URLs within the same origin will just use a[download]. Otherwise, it will first check if it supports cors header with a synchronous head request. If it does, it will download the data and save using blob URLs. If not, it will try to download it using a[download].

The standard W3C File API Blob interface is not available in all browsers. Blob.js is a cross-browser Blob implementation that solves this.

Saving a canvas

var canvas = document.getElementById("my-canvas");
canvas.toBlob(function(blob) {
    saveAs(blob, "pretty image.png");
});

Note: The standard HTML5 canvas.toBlob() method is not available in all browsers. canvas-toBlob.js is a cross-browser canvas.toBlob() that polyfills this.

Saving File

You can save a File constructor without specifying a filename. If the file itself already contains a name, there is a hand full of ways to get a file instance (from storage, file input, new constructor, clipboard event). If you still want to change the name, then you can change it in the 2nd argument.

// Note: Ie and Edge don't support the new File constructor,
// so it's better to construct blobs and use saveAs(blob, filename)
var file = new File(["Hello, world!"], "hello world.txt", {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(file);

Tracking image

Installation

# Basic Node.JS installation
npm install file-saver --save
bower install file-saver

Additionally, TypeScript definitions can be installed via:

# Additional typescript definitions
npm install @types/file-saver --save-dev

NPM DownloadsLast 30 Days