Suppose I want to use the Fetch API to upload a local file as part of FormData with Node.js.
If this were a browser, I might have a file or blob reference already, such as from a file input element. In that case, I just append the file reference to the FormData instance, and the user agent takes care of streaming it from disk, like so:
const formData = new FormData();
formData.append('file', fileInputElement.files[0]);
const res = await fetch(postURL, {
method: 'POST',
body: formData
});
Now, in the Node.js case, there is no file input element. All I have is a path on disk. How can I get a Blob or File reference from that?
Some things I've looked into:
- A simple
fs.open()
returns a FileHandle which is not something FormData can use. - A ReadableStream can't be used directly either.
- The Blob Stream Consumers utility will allow me to create a Blob from a ReadableStream, but it does this by buffering the entire contents of the stream in memory. That won't work as I'm uploading files that are multiple gigabytes.
Is there any way to get a File reference that FormData can use, for a local file on disk, with Node.js?