显示在服务器端运行的长进程的状态 [英] Show status of long process running on server side

查看:40
本文介绍了显示在服务器端运行的长进程的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在基于Node.js的Web应用程序中进行CSV导入.给定的大多数CSV文件都有成千上万的记录,并且需要几分钟的时间.

I'm working for CSV import in my Node.js based web app. Most given CSV files has tens of thousands of records, and it takes several minutes.

因此,在导入完成之前,我想向用户显示当前正在导入..."消息.

So until import finish, I want to show users "Currently importing..." message.

我要创建的内容类似于Github的分叉屏幕.按下仓库右上方的fork按钮后,它会显示消息"Forking/它只需要几秒钟."直到叉完成.另外,我想添加进度条以希望表示已处理记录的百分比.

What I want to create is similar to Github's forking screen. After you press fork button on top right of repo, it shows message that "Forking / It should only take a few seconds." until fork finishes. In addition, I want to add progress bar to indicate percentage of processed records hopefully.

目前,我的实现方式是:

Current my implementation is:

  1. 客户端发送带有CSV数据的请求
  2. 服务器处理收到的CSV并将记录插入数据库.
  3. 如果CSV有效,则服务器响应200.

但是在实施过程中,用户无法看到当前状态.甚至有时套接字会挂起.

But with implementation users cannot see current status. Even sometimes socket hangs up.

我正在考虑重新实现:

  1. 客户端发送带有CSV数据的请求
  2. 服务器响应200告知客户端已接收CSV
  3. 服务器开始处理收到的CSV并将记录插入到数据库中.

但是,我不知道:

  1. 客户如何知道导入已完成
  2. 客户端如何知道CSV处理和数据库插入中何时发生错误

如何实现服务器端?在此先感谢;)

How can implement server side? Thanks in advance ;)

推荐答案

您需要在此处使用 socket.io 来跟踪进度.收到CSV后,您的客户端即可连接到套接字.

You need to use socket.io here to keep track of the progress. As soon as you receive the CSV, your client could connect to socket.

服务器:

io.on('connection', function (socket) {
    console.log('CONNECTED');
    socket.join('progressSession');
});

您可以定期发出 progress 事件,以使客户端知道您已处理了多少条记录.(我希望您异步处理记录,或者至少可以在两者之间运行其他代码)

You can periodically emit progress event to let the client know how many records you've been processed. (I hope you're processing records asynchronously, or can at least run some other code in between)

io.sockets.in('progressSession').emit('progress', noOfRecords);

而且,客户端可以监听 progress 事件并将其显示给用户

And, Client can listen on progress event and show it to the user

var socket = io.connect('http://localhost:9000');
socket.on('progress' , function (status){
    console.log(status);
    // show status to the user
});

如果需要进一步说明,请发表评论.

Comment if need any more clarity.

这篇关于显示在服务器端运行的长进程的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆