【问题标题】:How to stream a file in post/put request with error handling?如何通过错误处理在 post/put 请求中流式传输文件?
【发布时间】:2020-02-02 23:59:07
【问题描述】:

这不是关于“重构以下代码的最佳方法是什么”的问题。它是关于“我如何重构以下代码以控制这两个异常”。


我有以下代码在 PUT 请求中流式传输文件。

import fs from 'fs'
import got from 'got' // it doesn't really matters if it's `axious` or `got`

async function sendFile(addressToSend: string, filePath: string) {
      const body = fs.createReadStream(filePath)
      body.on('error', () => {
        console.log('we cached the error in block-1')
      })
      try {
        const result = await client.put(addressToSend, {
          body,
        })
      } catch (e) {
        console.log('we cached the error in block-2')
      }
}

我正在尝试重构这段代码,让我有机会从一个地方捕获所有错误。

上述解决方案没有给我一种方法来测试stream 的失败。例如,如果我传递一个不存在的文件,该函数将同时打印 we cached the error in block-1we cached the error in block-2 但我没有办法重新抛出第一个错误或无论如何在测试中使用它。


注意:

我不确定解决它的最佳方法是否是这样做:

因为当我传递一个不存在的文件路径时,rej 函数将被调用两次,这是非常糟糕的做法。

function sendFile(addressToSend: string, filePath: string) {
  return new Promise(async (res, rej) => {
    const body = fs.createReadStream(filePath)
    body.on('error', () => {
      console.log('we cached the error in block-1')
      rej('1')
    })
    try {
      const result = await client.put(addressToSend, {
        body,
      })
      res()
    } catch (e) {
      console.log('we cached the error in block-2')
      rej('2')
    }
  })
}

【问题讨论】:

    标签: node.js error-handling node-streams


    【解决方案1】:

    我不太喜欢它,但这是我能想到的最好的:

    function streamFilePut(client: Got, url: string, filePath: string) {
      const body = fs.createReadStream(filePath)
      const streamErrorPromise = new Promise((_, rej) => body.on('error', rej))
    
      const resultPromise = new Promise((res, rej) => {
        return client
          .put(url, {
            body,
          })
          .then(res, rej)
      })
    
      return Promise.race([streamErrorPromise, resultPromise])
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-09
      • 2013-02-24
      • 2022-08-09
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多