通过NodeJS下载Tar文件

时间:2010-09-30 08:15:00

标签: javascript http node.js

我有两个nodejs http服务器,一个请求另一个tar文件。它通过浏览器测试工作正常,但我永远无法让第二台服务器正确粘合块。我对fwrite的尝试和这个一样无用

// Receives File
var complete_file = '';
response.on('data', function(chunk){
   complete_file += chunk 
}).on('end', function(){
    fs.writeFile('/tmp/test.tgz', complete_file, 'binary')
});

// Send File
fs.readFile('/tmp/test_send.tgz', function(err, data){
    if (err) throw err;
    response.writeHead('200', {
        'Content-Type' : 'application/x-compressed',
        'Content-Length' : data.length
    });
    response.write(data);
    response.end();
});

3 个答案:

答案 0 :(得分:7)

我设法让它工作但我使用可写流,这是客户端代码:

fs = require ('fs');

var http = require('http');
var local = http.createClient(8124, 'localhost');
var request = local.request('GET', '/',{'host': 'localhost'});
request.on('response', function (response) {
    console.log('STATUS: ' + response.statusCode);
    var headers = JSON.stringify(response.headers);
    console.log('HEADERS: ' + headers);
    var file = fs.createWriteStream('/tmp/node/test.gz');
    response.on('data', function(chunk){
        file.write(chunk);
        }).on('end', function(){
          file.end();
          });
    });
request.end();

答案 1 :(得分:7)

在较新版本的Node中,这已经发生了变化。

这是最新的,我添加了更多的逻辑来更加努力地完成下载,例如包围301,302 ......

function getFile(url, path, cb) {
    var http_or_https = http;
    if (/^https:\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/.test(url)) {
        http_or_https = https;
    }
    http_or_https.get(url, function(response) {
        var headers = JSON.stringify(response.headers);
        switch(response.statusCode) {
            case 200:
                var file = fs.createWriteStream(path);
                response.on('data', function(chunk){
                    file.write(chunk);
                }).on('end', function(){
                    file.end();
                    cb(null);
                });
                break;
            case 301:
            case 302:
            case 303:
            case 307:
                getFile(response.headers.location, path, cb);
                break;
            default:
                cb(new Error('Server responded with status code ' + response.statusCode));
        }

    })
    .on('error', function(err) {
        cb(err);
    });
}

答案 2 :(得分:2)

请求包呢?

你可以这样做:

request(fileurl).pipe(fs.createWriteStream(savetohere))