2017-08-29 99 views
1

我正在通過https加載.ndjson文件。我想在閱讀100行文件後關閉它。如何在Node.js中關閉https流

const amount = 100; 
    https.get(url, (res) => { 
    var { statusCode } = res; 

    if (statusCode !== 200) { 
     throw new Error(`Request Failed.\n Status Code: ${statusCode}`); 
    } 

    res.setEncoding('utf8'); 
    let rows = []; 
    res 
     .pipe(ndjson.parse()) 
     .on('data', function (obj) { 
     rows.push(obj); 
     if (rows.length === amount) { 
      this.end(); 
     } 
     }) 
     .on('end',() => { 
     resolve(rows); 
     }); 
    }).on('error', (e) => { 
    throw new Error(e.message); 
    }); 

但每次我試圖關閉流路,出現相同的錯誤消息:

Error: Could not parse row {"username"... 
    at DestroyableTransform.parseRow [as mapper] (C:\Users\thoma\Documents\GitHub\test\node_modules\ndjson\index.js:19:28) 
    at DestroyableTransform.flush [as _flush] (C:\Users\thoma\Documents\GitHub\test\node_modules\split2\index.js:44:21) 
    at DestroyableTransform.<anonymous> (C:\Users\thoma\Documents\GitHub\test\node_modules\readable-stream\lib\_stream_transform.js:138:49) 
    at Object.onceWrapper (events.js:314:30) 
    at emitNone (events.js:105:13) 
    at DestroyableTransform.emit (events.js:207:7) 
    at prefinish (C:\Users\thoma\Documents\GitHub\test\node_modules\readable-stream\lib\_stream_writable.js:596:14) 
    at finishMaybe (C:\Users\thoma\Documents\GitHub\test\node_modules\readable-stream\lib\_stream_writable.js:604:5) 
    at afterWrite (C:\Users\thoma\Documents\GitHub\test\node_modules\readable-stream\lib\_stream_writable.js:470:3) 
    at _combinedTickCallback (internal/process/next_tick.js:144:20) 

和流正常工作時不強行關閉的,所以它是不相關的ndjson文件。是否可以在請求中間關閉流?

回答

0

有幾種解決方案:

  1. 發送頭關閉連接:this.set("Connection", "close")
  2. 無休止感謝this.end()

我不知道哪一個是最好的。

所以,在你的例子中,你有一個問題,由於this(我建議你看看這個鏈接)。請嘗試以下代碼:

res 
    .pipe(ndjson.parse()) 
    .on('data', obj => { 
    rows.push(obj); 
    if (rows.length === amount) { 
     this.end(); 
    } 
    }) 
    .on('end',() => { 
    resolve(rows); 
    });