2016-04-08 24 views
0

Bir .json dosyasını arabelleğe almak için bir çalışma kodum var ve bu verileri bir sunucuya POST. Ben yapmasını ister neAkış uygulaması/json POST isteği

fs.readFile(filePath, 'utf-8', function (err, buf) { 

     if(err){ 
      reject(err); 
     } 
     else{ 
      const req = http.request({ 
       method: 'POST', 
       host: 'localhost', 
       path: '/event', 
       port: '4031', 
       headers: { 
        'Content-Type': 'application/json', 
        'Content-Length': buf.length 
       } 
      }); 


      req.on('error', reject); 

      var data = ''; 

      req.on('response', function (res) { 

       res.setEncoding('utf8'); 

       res.on('data', function ($data) { 
        data += $data 
       }); 

       res.on('end', function() { 

        data = JSON.parse(data); 
        console.log('data from SC:', data); 

        //call fn on data and if it passes we are good 
        resolve(); 
       }); 
      }); 

      // write data to request body 
      req.write(buf); 
      req.end(); 
     } 


    }); 

bunu arabelleğe önlemek ve sadece fs.createReadStream, bu yüzden böyle bir şey kullanmaktır:

fs.createReadStream(filePath, 'utf-8', function (err, strm) { 

    if(err){ 
     reject(err); 
    } 
    else{ 
     const req = http.request({ 
      method: 'POST', 
      host: 'localhost', 
      path: '/event', 
      port: '4031', 
      headers: { 
       'Content-Type': 'application/json', 
       // 'Content-Length': buf.length 
      } 
     }); 


     req.on('error', reject); 

     var data = ''; 

     req.on('response', function (res) { 

      res.setEncoding('utf8'); 

      res.on('data', function ($data) { 
       data += $data 
      }); 

      res.on('end', function() { 

       data = JSON.parse(data); 
       console.log('data from SC:', data); 

       //call fn on data and if it passes we are good 
       resolve(); 
      }); 
     }); 

     // write data to request body 
     req.write(strm); 
     req.end(); 
    } 


}); 

ama oldukça çalışır değil? Bunu yapmak mümkün mü? Doğru% 100 ise

cevap

0

Bu iş gibi görünüyor, ama emin değilim

const strm = fs.createReadStream(filePath); 


const req = http.request({ 
    method: 'POST', 
    host: 'localhost', 
    path: '/event', 
    port: '4031', 
    headers: { 
     'Content-Type': 'application/json', 
    } 
}); 


req.on('error', reject); 

var data = ''; 

req.on('response', function (res) { 

    res.setEncoding('utf8'); 

    res.on('data', function ($data) { 
     data += $data 
    }); 

    res.on('end', function() { 

     data = JSON.parse(data); 
     resolve(); 
    }); 
}); 

// write data to request body 
strm.pipe(req);