Previously to Node 18 releasing fetch/FormData we could do:
import FormData from 'form-data'
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
However with the global FormData I can no longer pass a stream - the error at the "my_file" line is:
Argument of type 'ReadStream' is not assignable to parameter of type 'string | Blob'
I know this is still experimental so potentially a bug or is there an alternative way to do this - besides reading the entire file as a string...
CodePudding user response:
Node v18's native FormData is an implementation of the w3 FormData interface so you need to use that API.
The append()
method accepts a Blob
so you should be able to use the blob
stream consumer
import { createReadStream } from 'node:fs';
import { blob } from 'node:stream/consumers';
// assuming a valid async context for brevity
const file = await blob(createReadStream("/foo/bar.jpg");
const formData = new FormData();
formData.append("my_file", file, "bar.jpg");