Last Modified : Sunday, Aug 18, 2024
JavaScript provides multiple ways to create files programmatically. Here are five common methods:
1. Using Blob
Blobs are binary large objects that allow you to store file data directly in JavaScript. You can easily create a file using the Blob constructor.
const data = new Blob(["Hello, world!"], { type: "text/plain" });
const file = new File([data], "example.txt");
console.log(file);
2. Using File Constructor
The File constructor is a more direct way of creating a file from an array of data.
const content = ["JavaScript File Creation"];
const file = new File(content, "file.txt", { type: "text/plain" });
console.log(file);
Accepts file content, name, and type as arguments.
3. Using FileReader and Blob
You can create a file using FileReader by reading a Blob and converting it to a base64 URL.
const blob = new Blob(["Some content"], { type: "text/plain" });
const reader = new FileReader();
reader.onloadend = () => {
console.log(reader.result);
};
reader.readAsDataURL(blob);
4. Using URL.createObjectURL
You can create a downloadable file URL using URL.createObjectURL with a Blob or File.
const blob = new Blob(["Download this content!"], { type: "text/plain" });
const fileURL = URL.createObjectURL(blob);
console.log(fileURL);
Generates a temporary URL to download or use the file created.
5. Using Streams API
The Streams API allows you to write file data in chunks, perfect for large files or real-time data.
const stream = new WritableStream({
write(chunk) {
console.log("Writing chunk:", chunk);
}
});
const writer = stream.getWriter();
writer.write("Chunk data");
writer.close();
Provides a mechanism to write chunks of data for large file creation or streaming.
These are quick ways to create files using JavaScript. Depending on your use case, you can pick the method that best suits your needs!
programming
os
javascript
npm