سؤال

لدي خادمان NodeJS HTTP ، يطلب أحدهما ملف TAR من الآخر. إنه يعمل بشكل جيد من خلال اختبار المتصفح ، لكن لا يمكنني أبدًا الحصول على الخادم الثاني لإلصاق القطع معًا بشكل صحيح. كانت محاولاتي مع اللوكيون عديمة الفائدة مثل هذا

// 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();
});
هل كانت مفيدة؟

المحلول

لقد تمكنت من جعلها تعمل ولكني أستخدم دفقًا قابل للكتابة بدلاً من ذلك ، هذا هو رمز العميل:

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();

نصائح أخرى

لقد تغير هذا في إصدارات أحدث من العقدة.

إليكم الأحدث ، وأضيف المزيد من المنطق لمحاولة جهد لإنهاء التنزيل مثل تشفير 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);
    });
}

ماذا عن حزمة الطلب؟

يمكنك ان تفعلها:

request(fileurl).pipe(fs.createWriteStream(savetohere))
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top