DEV Community

Jiri Spac
Jiri Spac

Posted on

How to send a file in form of a Buffer as a FormData in node.js

This is slightly modified excerpt from https://github.com/octet-stream/form-data#readme

import {Readable} from "stream"

import {FormData} from "formdata-node"

class BlobFromStream {
  #stream: Readable
  size: number

  constructor(stream: Readable, size: number) {
    this.#stream = stream
    this.size = size
  }


  stream() {
    return this.#stream
  }

  get [Symbol.toStringTag]() {
    return "Blob"
  }
}

const content = Buffer.from("Stream content")

const stream = new Readable({
  read() {
    this.push(content)
    this.push(null)
  }
})

const form = new FormData()

form.set("stream", new BlobFromStream(stream, content.length), "file.txt")

await fetch("https://httpbin.org/post", {method: "post", body: form})

Enter fullscreen mode Exit fullscreen mode

just in case anyone would be struggling with this same as me.

Top comments (0)