Search code examples
node.jsazure-blob-storageazure-blob-trigger

compress and write a file in another container with azure blob storage trigger in nodejs


i have to make an api call passing a compressed file as input. i have a working example on premise but I would like to move the solution in cloud. i was thinking to use azure blob storage and the azure function trigger. i have the below code that works for file but I don't know how to do the same with azure blob storage and azure function in nodejs

const zlib = require('zlib');
const fs = require('fs');

const def = zlib.createDeflate();

input = fs.createReadStream('claudio.json')
output = fs.createWriteStream('claudio-def.json')

input.pipe(def).pipe(output)

this code read a file as stream , compress the file and write another file as stream.

what I would like to do is reading the file any time I upload it in a container of azure blob storage, then I want to compress it and save in a different container with different name, then make an API call passing as input the compressed file saved in the other container

I tried this code for compressing the incoming file

const fs = require("fs");
const zlib = require('zlib');
const {Readable, Writable} = require('stream');
module.exports = async function (context, myBlob) {
    context.log("JavaScript blob trigger function processed blob \n Blob:", context.bindingData.blobTrigger, "\n Blob Size:", myBlob.length, "Bytes");
   // const fin = fs.createReadStream(context.bindingData.blobTrigger);
   const def = zlib.createDeflate();
   const s = Readable.from(myBlob.toString())
  context.log(myBlob);
  context.bindings.outputBlob = s.pipe(def)
};

the problem with this approach is that in the last line of the code

  context.bindings.outputBlob = s.pipe(def)

i don't have the compressed file, while if i use this

s.pipe(def).pipe(process.stdout)

i can read the compressed file

as you can see above i also tried to use the fs.createReadStream(context.bindingData.blobTrigger) that contains the name of the uploaded file with the container name, but it doesn't work

any idea? thank you


Solution

  • this is the solution

    var input = context.bindings.myBlob;
    
    var inputBuffer = Buffer.from(input);
    var deflatedOutput = zlib.deflateSync(inputBuffer);
    
    context.bindings.myOutputBlob = deflatedOutput;
    

    https://learn.microsoft.com/en-us/answers/questions/500368/compress-and-write-a-file-in-another-container-wit.html