我知道如何 fork 子进程,但我的要求是,我只想使用这个子进程来完成某些工作,例如,当单击按钮时,我需要处理表单数据以将其保存,如下所示。但是这个 post 路由必须由我创建的特定子进程执行,而不是其他子进程或主进程。
app.post('/saveuser', function(){
user.save();
})
最佳答案
post node 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 ......
关于node.js - 使用 Node.js 中的特定子进程运行作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53525739/