all files / src/lib/ zip.js

84.21% Statements 32/38
50% Branches 4/8
80% Functions 8/10
91.18% Lines 31/34
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56                   43×                   49× 49×              
var path = require('path')
var fs = require('fs')
var findit = require('findit')
var DecompressZip = require('decompress-zip')
var archiver = require('archiver')
var util = require('./util')
 
exports.extract = function(fpath, cb) {
  var zip = new DecompressZip(fpath)
  var zipPath = util.genTmpPath()
  var one = util.oneCallback(cb)
 
  zip
    .on('extract', function() {
      one(null, zipPath)
    })
    .on('error', one)
    .extract({path: zipPath})
}
 
var validOgrRe = /^\.(shp|kml|tab|itf|000|rt1|gml|vrt)$/i
exports.findOgrFile = function(dpath, cb) {
  var finder = findit(dpath)
  var found
 
  finder.on('file', function(file, stat) {
    if (validOgrRe.test(path.extname(file))) found = file
  })
  finder.on('error', function(er) {
    cb(er)
    finder.stop() // prevent multiple callbacks, stop at first error
  })
  finder.on('end', function() {
    Iif (!found) return cb(new Error('No valid files found'))
    cb(null, found)
  })
}
 
exports.createZipStream = function(dpath) {
  var zs = archiver('zip')
 
  fs.readdir(dpath, function(er, files) {
    Iif (er) return zs.emit('error', er)
 
    files.forEach(function(file) {
      var f = fs.createReadStream(path.join(dpath, file))
      zs.append(f, {name: file})
    })
    zs.finalize(function(er) {
      if (er) zs.emit('error', er)
    })
  })
 
  return zs
}