【问题标题】:How can I send a response multiple times during the code execution without sending all the responses at the last res.write如何在代码执行期间多次发送响应而不在最后一个 res.write 发送所有响应
【发布时间】:2021-12-11 21:54:24
【问题描述】:

您好,我一直在尝试解决这个问题,但无法在 node.js 中找到解决方案

我通常使用 Python 编写代码,并且能够使用生成器制作动态更新的 API

@app.route("/api/login")
def getQR():
    def generate_output():
        time.sleep(3)
        yield render_template_string(f"Hello 1\n")
        time.sleep(10)
        yield render_template_string(f"Hello 2\n")
    return Response(stream_with_context(generate_output()))

上面的代码在 3 秒后发送第一个响应“Hello 1”,然后等待 10 秒并将“Hello 2”添加到响应中。我正在尝试在 Node.js 中重新创建它,但不知道该怎么做。这是我当前的代码:

const server = http.createServer((req, res) => {
  if (req.url == "/" || req.url == "") {
          res.write("Hello 1\n");
          // Some code execution for 10s
          res.write("Hello 2\n")
          res.end();
  }
});

上面的代码等待10秒,然后发送“Hello 1\nHello 2\n” 我基本上是在尝试使用生成器在 Python 代码中实现我可以做的事情。任何解决方法/解决方案或建议将不胜感激。谢谢!

【问题讨论】:

    标签: node.js


    【解决方案1】:

    使用 python 流式传输内容

    根据python doc,generator用于数据流

    有时您想向客户端发送大量数据,远远超过您想保留在内存中的数据。但是,当您动态生成数据时,如何在不往返文件系统的情况下将其发送回客户端?

    答案是使用生成器和直接响应。

    检查这些参考资料:

    使用 nodejs 流式传输内容

    了解您需要的是数据流到您的浏览器传输大文件,而不是经典的res.send("hello"),基本上流程是:

    • 通常为文件创建流,不适用于字符串
    • 管道或将其写入响应
    • 结束交流

    这里是一个例子:

    import {createReadStream} from 'fs';
    import express from 'express';
    const app = express();
    
    app.get('/', (req, res) => {
      var readStream = createReadStream('./data.txt');
      readStream.on('data', (data) => {
        res.write(data);
      });
      readStream.on('end', (data) => {
        res.status(200).send();
      });
    });
    app.listen(3000);
    

    检查这些参考资料:

    【讨论】:

    • 非常感谢!感谢您的帮助:) 我想出了如何解决它
    【解决方案2】:

    我们将在 js 中创建一个 time.sleep() 替代方案。首先创建一个调用 setTimeout 的函数。

    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }
    

    使用await 调用此函数。详细了解 await here

    await sleep(3000) // waits for 3 seconds
    

    【讨论】:

      猜你喜欢
      • 2011-03-23
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      • 2011-05-17
      相关资源
      最近更新 更多