I have used the web streams on the frontend side to send big files into multiple chunks , but when it comes to the backend nodejs side i am not able to consume the received unit8array properly . all i got is unsupported file format while saving it to disk.
Here is my code :
import { Writable, Readable } from "stream";
import { writeFileSync } from "fs";
import { createServer } from "http";
import { pipeline } from "stream/promises";
const headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Method": "*",
"Access-Control-Allow-Headers": "*",
};
createServer(async (request, response) => {
if (request.method === "OPTIONS") {
response.writeHead(204, headers);
response.end();
return;
}
response.writeHead(200, headers);
async function* consumeStream() {
let body = Readable.toWeb(request).getReader();
let read = (await body.read()).value;
// received read as an uint8array
yield Buffer.from(read, "base64");
}
await pipeline(
consumeStream,
new Writable({
write(chunk, enc, cb) {
writeFileSync("./output.jpg", chunk);
cb();
},
})
);
}).listen(3000, () => {
console.log("Server started");
});