我知道如何派生子流程,但我的要求是,我想使用该子流程仅执行某些工作,例如,单击按钮时,我需要处理表单数据以将其保存,如下所示。但是此发布路线必须由我创建的特定子进程执行,而不是其他子进程或主进程。
app.post('/saveuser', function(){
user.save();
})
答案 0 :(得分:0)
发布节点v11.7.0发行了'worker_threads'模块,该模块不带实验标记。 非常适合用于单进程和多线程目的。 在11.7.0之前的版本中,您需要传递--experimental-worker标志才能访问它。
访问官方文档 Worker-Threads
/* app.js */
/* your code */
const { Worker, isMainThread, threadId, Worker, parentPort, workerData } = require('worker_threads')
console.log('is this main process', isMainThread)
app.post('/saveuser', function(){
let userSaveWorker = new Worker('name_of_another_script.js', { workerData: 'pass any type of data' })
userSaveWorker.on('message', returnData => {
// do whatever you wants to do with data returned from worker
// return response to user
})
userSaveWorker.unref() // this will allow worker to terminate
userSaveWorker.terminate() // this will forcefully terminate it
// you can use it in message listner
userSaveWorker.on('end', () => /* gets called when worker process gets terminated */);
})
现在用于工作进程的脚本
name_of_another_script.js
const { Worker, isMainThread, threadId, Worker, parentPort, workerData } = require('worker_threads')
console.log('is this main process', isMainThread)
console.log('data received from parentProcess', workerData)
/* your code */
// do process & then send message back to parent
parentPort.postMessage('your processed data or result any data type')
// this will be received in app.js as .on('message') listener
您甚至可以在没有其他脚本的情况下运行工作进程 将函数或代码作为字符串而不是文件名传递,并传递另一个选项{eval:true},它将起作用,您甚至还可以传递workerData ...