Top Related Projects
An HTML5 saveAs() FileSaver implementation
StreamSaver writes stream to the filesystem directly asynchronous
Detect the file type of a file, stream, or data
Quick Overview
rndme/download is a lightweight JavaScript library that simplifies the process of triggering file downloads from the browser. It provides a simple API to initiate downloads of various file types, including dynamically generated content, without the need for server-side processing.
Pros
- Easy to use with a simple and intuitive API
- Supports various file types and dynamically generated content
- Works across different browsers and devices
- No dependencies, making it lightweight and easy to integrate
Cons
- Limited documentation and examples
- Not actively maintained (last update was several years ago)
- May not support some advanced download scenarios
- Potential security concerns with client-side file generation
Code Examples
- Downloading a text file:
download("Hello, World!", "hello.txt", "text/plain");
- Downloading a dynamically generated CSV:
const csvContent = "Name,Age\nJohn,30\nJane,25";
download(csvContent, "users.csv", "text/csv");
- Downloading a base64-encoded image:
const base64Image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==";
download(base64Image, "image.png", "image/png");
Getting Started
To use the rndme/download library in your project, follow these steps:
- Include the library in your HTML file:
<script src="https://cdn.jsdelivr.net/gh/rndme/download/download.min.js"></script>
- Use the
download
function in your JavaScript code:
// Trigger a file download
download(data, filename, mimeType);
Replace data
with the content you want to download, filename
with the desired file name, and mimeType
with the appropriate MIME type for the file.
Competitor Comparisons
An HTML5 saveAs() FileSaver implementation
Pros of FileSaver.js
- More widely adopted and battle-tested in production environments
- Supports a broader range of browsers, including older versions
- Offers better handling of large files and memory management
Cons of FileSaver.js
- Slightly larger file size compared to download
- Less frequent updates and maintenance
- More complex API for some use cases
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");
download:
import download from 'downloadjs';
download("Hello, world!", "hello world.txt", "text/plain");
Both libraries aim to provide a simple way to trigger file downloads in the browser, but FileSaver.js offers more advanced features and broader compatibility at the cost of a slightly larger footprint and more complex API. download, on the other hand, provides a more straightforward interface for basic download needs but may lack some of the advanced features and wide browser support of FileSaver.js.
StreamSaver writes stream to the filesystem directly asynchronous
Pros of StreamSaver.js
- Supports streaming large files, reducing memory usage
- Works with various types of streams (ReadableStream, Blob, Response)
- Allows for progress tracking during downloads
Cons of StreamSaver.js
- Requires a service worker setup, which adds complexity
- Limited browser support compared to download
- May require additional configuration for cross-origin downloads
Code Comparison
StreamSaver.js:
import { createWriteStream } from 'streamsaver'
const fileStream = createWriteStream('filename.txt')
const writer = fileStream.getWriter()
writer.write(data)
writer.close()
download:
import download from 'downloadjs'
download(data, filename, mimeType)
Key Differences
StreamSaver.js is designed for handling large files and streams, making it suitable for applications dealing with substantial data transfers. It offers more granular control over the download process but requires additional setup.
download, on the other hand, provides a simpler API for quick, small-to-medium file downloads. It has broader browser support and is easier to implement for basic use cases.
Choose StreamSaver.js for large file handling and progress tracking, or download for straightforward, smaller downloads with minimal setup.
Detect the file type of a file, stream, or data
Pros of file-type
- Focuses specifically on file type detection, providing more comprehensive and accurate results
- Supports a wider range of file types, including less common formats
- Regularly updated with new file type signatures and improvements
Cons of file-type
- Limited to file type detection only, lacking download functionality
- Requires additional dependencies or code for file handling and downloading
- May have a steeper learning curve for users who need a simple download solution
Code Comparison
file-type:
import {fileTypeFromBuffer} from 'file-type';
const buffer = await readFile('path/to/file');
const fileType = await fileTypeFromBuffer(buffer);
console.log(fileType);
download:
import download from 'download';
await download('https://example.com/file.zip', 'dist');
console.log('Download complete');
Summary
file-type is a specialized library for detecting file types, offering extensive support for various formats. It's ideal for projects requiring accurate file type identification but lacks built-in download capabilities. download, on the other hand, provides a simpler solution for downloading files but doesn't include file type detection. The choice between the two depends on the specific needs of your project, with file-type being more suitable for complex file handling scenarios and download for straightforward file retrieval tasks.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
download
Summary
The download() function is used to trigger a file download from JavaScript.
It specifies the contents and name of a new file placed in the browser's download directory. The input can be a URL, String, Blob, or Typed Array of data, or via a dataURL representing the file's data as base64 or url-encoded string. No matter the input format, download() saves a file using the specified file name and mime information in the same manner as a server using a Content-Disposition HTTP header.
Getting and Using
Via NPM/Bower
npm install downloadjs
bower install downloadjs
require("downloadjs")(data, strFileName, strMimeType);
Simple global download
function via <script>
include
download(data, strFileName, strMimeType);
Included via AMD
require(['path/to/file'], function(download) {
download(data, strFileName, strMimeType);
});
Parameters
- data - The Blob, File, String, or dataURL containing the soon-to-be File's contents.
- strFileName - The name of the file to be created. Note that older browsers (like FF3.5, Ch5) don't honor the file name you provide, instead they automatically name the downloaded file.
- strMimeType - The MIME content-type of the file to download. While optional, it helps the browser present friendlier information about the download to the user, encouraging them to accept the download.
Example Usage
Plain Text
text string - live demo
download("hello world", "dlText.txt", "text/plain");
text dataURL - live demo
download("data:text/plain,hello%20world", "dlDataUrlText.txt", "text/plain");
text blob - live demo
download(new Blob(["hello world"]), "dlTextBlob.txt", "text/plain");
text url - live demo
download("/robots.txt");
text UInt8 Array - live demo
var str= "hello world", arr= new Uint8Array(str.length);
str.split("").forEach(function(a,b){
arr[b]=a.charCodeAt();
});
download( arr, "textUInt8Array.txt", "text/plain" );
HTML
html string - live demo
download(document.documentElement.outerHTML, "dlHTML.html", "text/html");
html Blob - live demo
download(new Blob(["hello world".bold()]), "dlHtmlBlob.html", "text/html");
ajax callback - live demo
(note that callback mode won't work on vanilla ajax or with binary files)
$.ajax({
url: "/download.html",
success: download.bind(true, "text/html", "dlAjaxCallback.html")
});
Binary Files
image from URL - live demo
download("/diff6.png");
Image via ajax for custom filename - live demo
var x=new XMLHttpRequest();
x.open( "GET", "/diff6.png" , true);
x.responseType="blob";
x.onload= function(e){download(e.target.response, "awesomesauce.png", "image/png");};
x.send();
Compatibility
download.js works with a wide range of devices and browsers.
You can expect it to work for the vast majority of your users, with some common-sense limits:
- Devices without file systems like iPhone, iPad, Wii, et al. have nowhere to save the file to, sorry.
- Android support starts at 4.2 for the built-in browser, though chrome 36+ and firefox 20+ on android 2.3+ work well.
- Devices without Blob support won't be able to download Blobs or TypedArrays
- Legacy devices (no a[download]) support can only download a few hundred kilobytes of data, and can't give the file a custom name.
- Devices without window.URL support can only download a couple megabytes of data
- IE versions of 9 and before are NOT supported because the don't support a[download] or dataURL frame locations.
FAQ
Can I tell when a download is done/canceled?
No.How can I style the temporary download link?
Define CSS class styles for.download-js-link
.What's up with Safari?
I don't know either but pull requests that improve the situation are welcome.Why is my binary file corrupted?
Likely: an incorrect MIME or using jQuery ajax, which has no bin support.How big of files work?
Depends, try yourself: File Echo Demo... I do a 1GB dl routinely on a thinkpad...
Change Log (v4.1)
- 2008 :: landed a FF+Chrome compatible way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
- 2012 :: added named files via a[download], msSaveBlob() for IE (10+) support, and window.URL support for larger+faster saves than dataURLs
- 2014 :: added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support
- 2015 :: converted to amd/commonJS module with browser-friendly fallback
- 2015 :: 4.1 added direct URL downloading via a single URL argument.
- 2016 :: 4.2 added large dataURL support, a more semantic codebase, and hidden temp links
- 2017 :: added support for empty dataURLs
- 20XX :: ???? Considering Zip, Tar, and other multi-file outputs, Blob.prototype.download option, and more, stay tuned folks.
Top Related Projects
An HTML5 saveAs() FileSaver implementation
StreamSaver writes stream to the filesystem directly asynchronous
Detect the file type of a file, stream, or data
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot