electron使用new Worker写入文件导致浏览器崩溃

main.js

let data1 = [];
let data2 = [];
for (let i = 0;i < 500000;i++) {
    let j = i * 500.0 / 60000.0;
    data1.push([j, 200 * Math.random() + 100]);
    data2.push([j, 400 * Math.random() + 100]);
}
let params = {
    type: 'xls',
    data: { data1, data2 },
    filename: 'text.xls',
};
let worker = new Worker('worker.js');
worker.onmessage = (ev) => {
console.log('写入完成'); worker.terminate(); }; worker.postMessage(
params);

worker.js

const fs = require( "fs" );

self.onmessage = function (e) {
    let data = e.data;
    console.log(data);
    if (data.type === "xls") {
        //todo 写入文件流
        let writeStream = fs.createWriteStream(data.filename, { encoding: 'utf8' });
        //读取文件发生错误事件
        writeStream.on('error', (err) => {
            console.error('发生异常:', err);
       self.postMessage({ success: false, message: err }); });
//已打开要写入的文件事件 writeStream.on('open', (fd) => { console.log('文件已打开:', fd); let i = 0; let value = "x\ty\ty1\n"; function write() { if (i >= data.data.data1.length) { writeStream.end(); setTimeout(() => {//todo 不知道为什么,立即发送报错,延迟发送没问题,这样electron窗口就不会崩溃 self.postMessage({ success: true, message: 'complete' }); }, 500); return; } value = data.data.data1[i][0] + "\t" + data.data.data1[i][1] + "\t" + data.data.data2[i][1] + "\n";
          i++; writeStream.write(value, ()
=> { write(); }); } writeStream.write(value, () => { write(); }); }); //文件已经就写入完成事件 writeStream.on('finish', () => { console.log('写入已完成..'); }); //文件关闭事件 writeStream.on('close', () => { console.log('文件已关闭!'); }); } };

 

转载于:https://www.cnblogs.com/caiyingyong/p/11597964.html

发布了0 篇原创文章 · 获赞 16 · 访问量 9万+
展开阅读全文
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览