UNPKG

1.86 kBJavaScriptView Raw
1var os = require('os');
2var fs = require('fs');
3var path = require('path');
4var request = require('request');
5var async = require('async');
6var unzip = require('unzip2');
7var ncp = require('ncp').ncp;
8var debug = require('debug')('4front:cli:template');
9
10module.exports.extract = function(url, destDir, callback) {
11 var tempDir = path.join(os.tmpdir(), new Date().getTime().toString());
12 debug("downloading zip to %s", tempDir);
13
14 var sourceDir;
15 async.series([
16 function(cb) {
17 // make a temp directory to download the zip to
18 fs.mkdir(tempDir, cb);
19 },
20 function(cb) {
21 // download the zip to the tmp directory
22 request.get({url: url, strictSSL: false})
23 .pipe(unzip.Extract({path: tempDir}))
24 .on('error', function(err) {
25 return cb(err);
26 })
27 // unzip emits the close event once contents are fully extracted to disk
28 .on('close', cb);
29 },
30 function(cb) {
31 // Look at the contents of the extracted zip. If there is a single
32 // directory at the root, discard it and advance to it's own contents.
33 fs.readdir(tempDir, function(err, files) {
34 if (files.length === 1) {
35 // If the root of the extracted contents is a single directory,
36 // then make the extractRoot that directory.
37 fs.stat(path.join(tempDir, files[0]), function(err, stats) {
38 if (err) return cb(err);
39
40 if (stats.isDirectory() === true)
41 sourceDir = path.join(tempDir, files[0]);
42
43 return cb();
44 });
45 }
46 else
47 cb();
48 });
49 },
50 function(cb) {
51 if (!sourceDir)
52 sourceDir = tempDir;
53
54 debug("copying from %s to %s", sourceDir, destDir);
55 // Now recursively copy to the destination directory
56 ncp(sourceDir, destDir, cb);
57 }
58 ], callback);
59};