Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
Trying to return a stream-buffer from a function

I am attempting to create a zip file containing a csv file and return it from a function as a buffer. The code I have is as follows:

const archiver = require('archiver');
const streamBuffers = require("stream-buffers");

createZipFromCsv(csv) {

  var myWritableStreamBuffer = new streamBuffers.WritableStreamBuffer({
    initialSize: (100 * 1024),   // start at 100 kilobytes.
    incrementAmount: (10 * 1024) // grow by 10 kilobytes each time buffer overflows.
  });

  myWritableStreamBuffer.on('finish', () => {
    console.log(myWritableStreamBuffer.getContents())
    return Promise.resolve(myWritableStreamBuffer.getContents());
  });

  const archive = archiver('zip');
  archive.pipe(myWritableStreamBuffer);
  archive.append(csv, { name: 'csvName.csv' });
  archive.finalize();

}

And the function call:

const buffer = await createZipFromCsv("some,csv,data");
console.log(buffer)

however, the buffer console log after the function call is undefined. The console log inside the on finish returns a good buffer, but only after the console log after the function call. I'm confused why the function is returning before the buffer has finished writing.

Any help appreciated!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to wrap your code in a promise that you return and then resolve/reject appropriately. Here's one way to do that:

const archiver = require('archiver');
const streamBuffers = require("stream-buffers");

createZipFromCsv(csv) {

    return new Promise((resolve, reject) => {
        const myWritableStreamBuffer = new streamBuffers.WritableStreamBuffer({
            initialSize: (100 * 1024), // start at 100 kilobytes.
            incrementAmount: (10 * 1024) // grow by 10 kilobytes each time buffer overflows.
        });

        myWritableStreamBuffer.on('finish', () => {
            resolve(myWritableStreamBuffer.getContents());
        });

        myWritableStreamBuffer.on('error', reject);

        const archive = archiver('zip');
        archive.pipe(myWritableStreamBuffer);
        archive.append(csv, { name: 'csvName.csv' });
        archive.finalize();

    });
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!