-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathunzipOne.js
42 lines (40 loc) · 1.26 KB
/
unzipOne.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const yauzl = require('yauzl')
const { basename, join } = require('path')
const fs = require('fs')
/**
* unzip and write file 'fn' to 'dstDir'
* @param {String} srcZip source zipfile
* @param {String} fn to unzip
* @param {String} dstDir destination dir
* @returns {Promise<String>} to output filename if successful, or falsy if the file was not found.
*/
function unzipOne (srcZip, fn, dstDir) {
const outFile = join(dstDir, fn)
return new Promise((resolve, reject) => {
yauzl.open(srcZip, { lazyEntries: true },
(err, zipfile) => {
/* istanbul ignore next */
if (err) return reject(err)
zipfile.readEntry()
zipfile.on('entry', entry => {
if (basename(entry.fileName) === fn) {
zipfile.openReadStream(entry, (err, readStream) => {
/* istanbul ignore next */
if (err) return reject(err)
readStream.on('end', () => {
zipfile.close()
resolve(entry.fileName)
})
readStream.pipe(fs.createWriteStream(outFile))
})
} else {
zipfile.readEntry()
}
})
zipfile.on('end', () => {
resolve() // not found
})
})
})
}
module.exports = unzipOne