Javascript Browser File Download

0.4.12 · active · verified Sun Apr 19

The `js-file-download` package offers a focused JavaScript utility function to initiate browser-driven file downloads directly from client-side data. It enables applications to save JavaScript-generated content, such as dynamically created CSVs, JSON blobs, or any string data, into a local file on the user's system without requiring a server roundtrip. The current stable version, 0.4.12, includes recent fixes for specific browser compatibility issues, notably on Apple devices, indicating ongoing maintenance. Its release cadence appears to be driven by bug fixes and compatibility updates rather than feature additions. Key differentiators include its lightweight footprint, single-function API, and direct utility for client-side data persistence, making it an efficient choice for scenarios where data is already available in the browser and needs to be downloaded.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to download various types of client-side generated content (text, JSON, CSV) using the `fileDownload` function, including specifying MIME types.

import fileDownload from 'js-file-download';

// Example 1: Download a simple text string
const textData = 'Hello, world!\nThis is some client-generated text.';
fileDownload(textData, 'hello.txt');

// Example 2: Download JSON data
const jsonData = {
  id: 1,
  name: 'Product A',
  description: 'A fantastic product generated on the client-side.',
  timestamp: new Date().toISOString(),
};
const jsonString = JSON.stringify(jsonData, null, 2);
fileDownload(jsonString, 'data.json', 'application/json');

// Example 3: Simulate downloading a CSV file with custom content type
const csvData = `Name,Age,City\nAlice,30,New York\nBob,24,London\nCharlie,35,Paris`;
fileDownload(csvData, 'report.csv', 'text/csv');

// In a browser environment, these calls would trigger actual downloads.
// For security and browser sandbox reasons, actual file saving does not happen in a Node.js console.
console.log('File download attempts initiated. Check your browser downloads.');

// Illustrative environment variable usage, not directly related to file-download functionality.
const API_KEY = process.env.MY_API_KEY ?? 'sk-example-key';
if (API_KEY === 'sk-example-key') {
  console.warn('Warning: MY_API_KEY environment variable is not set. Using a dummy key.');
}

view raw JSON →