使用GitLab API和Node.js下载GitLab存储库存档

时间:2017-04-27 12:22:36

标签: javascript node.js download gitlab gitlab-api

我想从我的GitLab存储库下载(而不是克隆)存档,但是我收到此错误

  

不正确的标题检查(Zlib._handle.onerror)

这是我的功能:

var fs = require('fs');
var url = require('url');
var https = require('https');
var path = require('path');
var targz = require('tar.gz');

function downloadFile(source, destination, name) {
    var options = {
        host: url.parse(source).host,
        port: 443,
        path: url.parse(source).pathname
    };

    var file = fs.createWriteStream(destination + path.sep + name);

    https.get(options, function(res) {
        res.on('data', function(data) {
            file.write(data);
        }).on('end', function() {
            file.end();
            console.log('File ' + name + ' downloaded to ' + destination);

            targz().extract(destination + '/' + name, destination)
                .then(function(){
                    console.log('Job done!');
                })
                .catch(function(err){
                    console.log('Something is wrong ', err.stack);
                });
        });
    });
}

下载的文件是tar.gz的类型。我尝试设置一些标题但不成功。源参数类似于:https://gitlab.com/api/v3/projects/:ID/repository/archive?token=XXYYZZ

请帮忙吗?

1 个答案:

答案 0 :(得分:2)

问题是https模块没有正确下载您的文件,导致tar.gz模块的提取错误。

您可以使用与request tar.gz配合的var request = require('request'); var targz = require('tar.gz'); function downloadFile(source, destination, cb) { var read = request.get(source); var write = targz().createWriteStream(destination); read.pipe(write); write.on('finish', function() { cb(null); }); write.on('error', function(err) { cb(err); }); } var source = "https://gitlab.com/api/v3/projects/:ID/repository/archive?token=XXYYZZ"; var destination = "/home/user/some/dir"; downloadFile(source, destination, function(err) { if (err) { console.log('Something is wrong ', err.stack); } else { console.log('Job done!'); } }); 模块将提取直接传送到目标文件夹:

finish

请注意,要发送1.0.2个活动,您需要tar.gz的版本npm install tar.gz@1.0.2 (请参阅createWriteStream):

{{1}}