2016-04-08 12 views
0

Ich habe Arbeitscode, um eine .json-Datei zu puffern und dann diese Daten an einen Server zu senden.Stream-Anwendung/Json POST-Anfrage

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


    }); 

was würde ich stattdessen tun möchte, ist es zu vermeiden, Pufferung und nur fs.createReadStream verwenden, so etwas wie so:

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


}); 

aber das funktioniert nicht ganz? Ist es möglich, dies zu tun?

Antwort

0

Dies scheint zu funktionieren, aber nicht sicher, ob es 100% richtig

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