1

我正在.ndjson通过 https 加载文件。我想在读取 100 行文件后关闭它。

  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文件无关。是否可以在请求中间关闭流?

4

1 回答 1

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);
  });
于 2017-08-29T14:23:33.900 回答