FileSaver.js is a classic client-side JavaScript library used to save files directly onto a user’s local machine without needing to send data back to a web server. It acts as a wrapper around the browser’s Blob object and download mechanics, ensuring wide cross-browser compatibility. Installing and Importing the Library
You can integrate FileSaver.js into your project by pulling it from a CDN or installing it locally via package managers.
Using a CDN (for pure HTML/JS):Include the script tag directly into your HTML document. Use code with caution.
Using NPM or Yarn (for modern frameworks):Install the package in your terminal. npm install file-saver Use code with caution.
Then, import it into your JavaScript or TypeScript component: javascript import { saveAs } from ‘file-saver’; Use code with caution. How to Use FileSaver.js
The library revolves around a single core method: saveAs(blob/file/url, filename). 1. Saving Text Files
To save text data, wrap your string inside a browser-native Blob object, specify the MIME type, and pass it to saveAs. javascript
// 1. Define the data string const textData = “This is the content of my local file.”; // 2. Create a Blob with a plain text MIME type const blob = new Blob([textData], { type: “text/plain;charset=utf-8” }); // 3. Trigger the prompt to download locally saveAs(blob, “document.txt”); Use code with caution. 2. Saving JSON Data
Exporting app configurations, data objects, or states as JSON files follows the exact same logical workflow. javascript
const userData = { name: “Alex”, age: 30, role: “Admin” }; // Stringify JSON data and assign application/json MIME type const jsonBlob = new Blob([JSON.stringify(userData, null, 2)], { type: “application/json” }); saveAs(jsonBlob, “profile-data.json”); Use code with caution. 3. Saving Files via Remote URLs
If you want to trigger a download for an existing asset hosted on a server (like an image or a PDF), you can feed the URL directly into saveAs. How to use FileSaver.js to save text files – Stack Overflow
Leave a Reply