Rob
Rob

Reputation: 3459

Refactoring promise to return from function

I am using JSZip to unzip a directory, which runs async. I want to write a function that unzips a file and returns the files associated with it, like this:

function unzipFile(filename){
  const zipper = new jsZip()
  return fs.readFile(filename, function(err, data) {
    return jsZip.loadAsync(data).then(function(zip) {
      return zip.files
    })
  })
}

but this is just return undefined. How can I make this async so that it returns the unzipped directory in a single function, and if I wanted to set a variable equal to its output would await its completion?

Upvotes: 1

Views: 470

Answers (2)

Bergi
Bergi

Reputation: 664503

You will need to promisify fs.readFile:

function readFileAsync(filename) {
    return new Promise((resolve, reject) => {
        fs.readFile(filename, function(err, data) {
            if (err) reject(err);
            else resolve(data);
        });
    });
}

Then you can chain onto that:

async function unzipFile(filename) {
    const zipper = new jsZip();
    const data = await readFileAsync(filename);
    const zip = await zipper.loadAsync(data);
    return zip.files;
}

Upvotes: 1

Jaromanda X
Jaromanda X

Reputation: 1

You'll need to promisify fs.readFile first - then just a regular Promise chain should do the trick

e.g.

function unzipFile(filename){
    return new Promise((resolve, reject) => fs.readFile(filename, function(err, data) {
        if(err) {
            return reject(err);
        }
        resolve(data);
    }))
    .then(data => new jsZip().loadAsync(data))
    .then(zip => zip.files);
}

Upvotes: 5

Related Questions