我正在开发一个使用电子框架的桌面应用程序,我必须使用sqlite数据库来处理应用程序数据。我决定使用better-sqlite3是因为:
node-sqlite3快得多但是在某些情况下,当我执行一个需要一段时间来响应的查询时,应用程序UI在查询结束之前不会响应用户。
如何在另一个线程中运行一些db查询?或者运行它们异步化(如node-sqlite3)?
抱歉英语不太好
发布于 2018-02-01 08:28:28
节点允许您使用单独的进程。(线程是另一回事,唉,没有WebWorkers :(尽管您可以在库中找到一个线程附加项)。
编辑:自从我最初发布这个答案以来,Node就添加了worker_threads。还没有试过/不知道它们是否与更好的sqlite一起工作.结束编辑
我遇到了与您相同的问题--需要同步代码才能运行而不阻塞主线程,并且我使用了一个子进程。它是为了更好
问题是,如何处理io流和sigints等控件并不明显,取决于您是在windows上运行还是在posix上运行。
我使用分叉子进程并将静默选项设置为true来执行同步db工作。
如果需要控制该进程或进度更新报告,则在同步操作期间返回到gui的主进程;我在子进程代码的各个点使用fileSystem writeFileSync / readFileSync对子进程stdin/out进行读写,从而控制/与子进程通信(在同步操作期间不能使用正常的进程间通信api,因为这是事件驱动的,在同步代码运行时不能操作。虽然你可以混合和匹配这两种类型的io)
分叉式儿童加工的实例;
//parent.js and child.js in same folder
//parent.js
process.on('exit', (code) => {
console.log(`Parent to exit with code: ${code}`);
});
const readLine = require("readline") ;
const cp = require('child_process');
var forkOptions = {
//execArgv:['--inspect-brk'], // uncomment if debugging the child process
silent:true // child gets own std pipes (important) whch are piped to parent
};
var childOptions = [] ;
const child = cp.fork(`./child.js`,childOptions,forkOptions);
//for messages sent from child via writeSync
const childChannel = readLine.createInterface({
input: child.stdout
}).on("line",function(input){
console.log("writeSync message received from child: " + input) ;
});
//for messages sent from child via process.send
child.on('message', (m) => {
console.log("process.send message received from child: " + m) ;
});
// Child.js
process.on('exit', (code) => {
console.log(`Child to exit with code: ${code}`);
});
const fs = require('fs');
function doSyncStuff(){
for(let i = 0 ; i < 20 ; i++){
//eg. sync db calls happening here
process.send(`Hello via process.send from child. i = ${i} \n`); // async commms . picked up by parent's "child.on" event
fs.writeFileSync(process.stdout.fd,`Hello via writeFileSync from child. i = ${i} \n`) ; // sync comms. picked up by parent's readLine listener ("process" here is the child )
}
}
doSyncStuff();https://stackoverflow.com/questions/48537273
复制相似问题