Working with Files
Working with files can be tricky in Node.js and the browser. Here are the general do’s and don’ts, as well as examples on how to handle files.
Memory Usage
When working with files, always be mindful of memory usage. Reading a large file into memory can cause your application to crash. If you need to read a large file, consider using streams.
In the browser
All modern browsers and Deno implement the File API. It is the recommended way to interact with the Fileforge API and SDKs in the browser.
The File
object associates a content stream with important metadata like the file’s name, size, and MIME type.
Creating a File instance
Creating a File object from a Blob, Buffer or String
Creating a File object from a File input
Consuming a File
Creating a URL for a File
Creating an object URL for a file is useful when you need to display the file in a specific context like an <iframe>
, or if you want to trigger a download.
Converting a ReadableStream to a File
This example is only applicable in browser-like environments. In Node.js
environments, the SDK response is a Readable
rather than a ReadableStream
.
When interacting with API methods that return a file, the SDK will return a ReadableStream
. Here is how to convert it back to a File
object.
In Node.js
Node.js does not have a built-in File
object like the browser. We recommend working with the polyfill from formdata-node
that provides a similar API to the browser. formdata-node
is shipped with the Fileforge SDK.
Reading a File
From an existing file
From an existing file, streamed
Without using File
In some cases, you may not want or need to use the File
object. You can work with the file directly using streams. Note that some endpoints, such as generate
and merge
rely on file names to determine root files and links. Not passing Files may cause issues with these endpoints.
Consuming a SDK response
When interacting with API methods that return a file, the SDK will return a Readable
. Here is how to consume it.