如何在节点

我正在使用node-mssql和node.js v10.16.0。我使用它来流式传输大量数据,并使用websocket将数据发送到客户端,并且效果很好。在前端,我有vue.js。

我的问题是,流开始播放时不会停止。即使用户更改了前端应用程序中的选项卡,即使我关闭了websocket连接,大量数据仍会继续流式传输。但是,保持流数据毫无意义,因为用户位于另一个选项卡上并且看不到数据。

我可以在用户使用Websocket更改选项卡之前将一些数据从客户端发送到服务器,以便可以警告启动该流的同一节点函数以停止该流。但是我不能让流以某种方式停止。

这是我的代码:

const sql = require('mssql');
const pool = new sql.ConnectionPool(config);
const poolConnect = pool.connect();

const testStream = (ws,id) => {       
    let request;
    //if id came as 'close',then user changed tab,so stop streaming
    if (id == 'close') {
       request.pause();
       sql.close();
       return;
    }

    poolConnect.then((pool) => {   
      request = new sql.Request(pool);
      request.stream = true;   
      request
      .input('id_param',sql.Int,parseInt(id))
      .query('SELECT * FROM table WHERE id = @id_param ')  

      let rowsToProcess = [];
      let data = [];  

      request.on('row',row => {   
        rowsToProcess.push(row); 
        if (rowsToProcess.length >= 20) {  
          request.pause();
          processRows(false);
        } 
      });

      request.on('done',() => {      
        processRows(true); 
        sql.close(); 
      });

      const processRows = () => { 
          rowsToProcess.forEach((item)=>{ 
                data.push(item.name);   
                data.push(item.surname);   
                data.push(item.age);   
            });    
          ws.send(JSON.stringify({ success:true,message: data }));
          rowsToProcess = [];
          data = []; 
         setTimeout(
          ()=>{request.resume();},100
         );//make it asynch with timeout
      }//processRows 

    }) //poolConnect.then

告诉关闭流的数据实际上到达该功能,然后转到该部分:

    if (id == 'close') {
       request.pause();
       sql.close();
       return;
    }

但是,问题是request is undefined,因为它已经定义并正在运行,我想我可以将其注释掉,只使用sql.close();,但流会继续进行。

我该怎么办?

谢谢

wuchun198799 回答:如何在节点

IMO request is undefined错误是合乎逻辑的,因为此时未为request分配任何内容。您可以在request函数外部声明testStream变量。但是,仍然存在问题。如果testStream被执行两次(或更多次),则request将在第二次调用时被修改。因此,您应该维护一个数组/映射或其他内容以分别标识每个requestpause。另外,如果request是流,那么您应该可以调用.destroy()破坏流。

本文链接:https://www.f2er.com/2899307.html

大家都在问