我正在使用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();
,但流会继续进行。
我该怎么办?
谢谢