0
我有一个node.js项目建立在electron-vue上,它利用电子,babel,webpack和vue。我已经构建了一个简单的vue SPA,但是我发现单线程本质并不适合需要做大量数据获取和处理。利用子进程中的ES6
我的第一个想法是创建子进程。我创建了一个VUE组件的滋生和管理子进程:
startProcess() {
const path = require('path');
const fs = require('fs');
const child_process = require('child_process');
const app_root = require('app-root-path');
const service_root = '/src/main/services/';
const service_path = app_root.resolve(path.format({dir: service_root, name: this.service, ext: '.js'}));
if (fs.existsSync(service_path)) {
this.service_process = child_process.fork(service_path, [], { silent: true });
this.service_process.on('close', this.onChildClose);
this.service_process.on('error', this.onChildError);
this.service_process.on('disconnect', this.onChildDisconnect);
this.service_process.on('message', this.onChildMessage);
this.service_process.send({ message: "hello" });
console.log(`${this.service} started successfully`);
} else {
console.log(`${service_path} does not exist`);
console.log(`${this.service} cannot start!`);
}
}
而且我的例子过程:
const path = require('path');
const service = path.basename(__filename);
process.on('disconnect', (m) => {
console.log(`${service} disconnected, exiting...`);
process.exit();
});
process.on('exit', (m) => {
console.log(`${service} has stopped`);
});
process.on('message', (m) => {
if (m.message === "ping") {
process.send({message:"pong"});
} else {
}
console.log(`parent > ${service}:`, m);
});
function tick()
{
//process.send({ message: `${service} update` });
}
setInterval(tick, 500);
这工作出奇地好。 IPC允许我向每个子进程泵送消息,允许我将多个进程中的大数据任务委托给多个进程。但是,有一个障碍。
我无法在子进程中使用ES6功能。
例如,尝试import
和export
类会导致错误。通过使用babel-node
运行这些子进程,它们看起来可以正常工作,但我宁愿不要从我的应用程序单独安装babel。根据http://node.green,这些应该在nodejs v8.1.2下兼容。
我该如何利用这些功能?有没有更好的方法来构建我的应用程序,以便在此尝试进行?
它是ES6规范的一部分,但它尚未在Node中实现。你可以在这里找到更多关于[这里](https://medium.com/the-node-js-collection/an-update-on-es6-modules-in-node-js-42c958b890c) –
除此之外,Electron使用v7.4.0。 – RoyalBingBong