Search code examples
node.jsbufferfsnode-streams

How to create a file from string and send it via FormData


I have a svg in form of a string. I want to convert that string into a file and send it via FormData to another API.

I found a way how it works but that includes creating a file locally (with fs) and then creating a readStream from the just created file. Processing many files this is super slow and ends in a timout most of the time.

fs.writeFile('file.svg', svgString, async () => {
            const fr = fs.createReadStream('file.svg');
            const formData = new FormData();
            formData.append('media', fr);

            const response = await Axios.post(route, formData, {...}
            });
        });

Here is my (failing) approach using Buffer and Readable:

// Create readable from svg string
const b = Buffer.from(svgString, 'utf-8');
const r = Readable.from(b);

const formData = new FormData();
formData.append('media', fr);

const response = await Axios.post(route, formData, {...});

This method is not giving the same result as the first. I then get a error from the external API.

The question is how do I get the same result as in the first approach, without writing local files to the disk.

Thanks in advance!


Solution

  • Well, the problem was less the buffer than the form data.

    The API required the data to have a filename, which it automatically had when read from an actual file with fs.createReadStream('file.svg');

    So when creating a Buffer I had to add it manually. So final working solution is:

    const svgBuffer = Buffer.from(svgString);
    const formData = new FormData();
    formData.append('media', svgBuffer, {
        filename: 'content.svg'
    });