Skip to content

Sending a file using fetch() without first buffering it in memory #61812

@gabrielschulhof

Description

@gabrielschulhof

The following was possible with Node.js 22:

const { Readable } = require('node:stream');
const fs = require('node:fs');

const accessToken = process.env.ACCESS_TOKEN;
const url = process.env.URL;
const filename = process.env.FILENAME;

class MyFile {
  constructor(options) {
    Object.assign(this, options);
    this[Symbol.toStringTag] = 'File';
  }
}

;(async () => {
  const stream = Readable.toWeb(fs.createReadStream(filename));
  const form = new FormData();

  form.set('file', new MyFile({
    stream: () => stream,
    name: filename,
    type: 'application/octet-stream'
  }));

  const result = await fetch(url, {
    method: 'PUT',
    body: form,
    headers: {
      authorization: `Bearer ${accessToken}`
    }
  });

  console.log(`ok: ${result.ok}`)

  console.log(JSON.stringify(await result.json(), null, 2));
})()

IOW, one could supply a pseudo-File instance to fetch(), which would accept it because of a loose isBlobLike() type check in its implementation, and would then stream it into a part of a multipart form request.

In Node.js 24, this type check is now much stricter in that the instance must be an instance of Blob, which causes the above code to simply upload the string [object File] instead of the file itself.

Thus, in Node.js 24, is there a way to send a file using fetch() without first buffering it in memory?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions