简体   繁体   English

Nodejs 全局变量不能在单独的进程中工作

[英]Nodejs global variable not working in separate process

I am using queues with bullJS library.我在 bullJS 库中使用队列。 In entry point, I have defined global.db variable which I can use everywhere.在入口点,我定义了global.db变量,我可以在任何地方使用它。

On bull's documentation I read separate processes are better so I created a new separate process in a file and I'm doing在公牛的文档中,我读到单独的进程更好,所以我在文件中创建了一个新的单独进程,我正在做

queue.process("path-to-the-file")

And in that file I can't use my global variable, it is undefined.在那个文件中我不能使用我的全局变量,它是未定义的。 Please suggest a solution or why is this happening?请提出解决方案或为什么会这样?

I am seeing if the file is included as module, it knows global variable but if it's referenced directly like I'm doing above, it doesn't know global variables.我正在查看文件是否作为模块包含在内,它知道全局变量,但如果像我上面那样直接引用它,它就不知道全局变量。

const Queue = require("bull");
const queue = new Queue("update-inventory-queue");
const updateInventoryProcess = require("../processes/updateInventory");
queue.process(updateInventoryProcess);

The above snippet works but now the updateInventoryProcess is not separate process, it is just a function imported by the module.上面的代码片段有效,但现在updateInventoryProcess不是单独的进程,它只是模块导入的 function。

As you've discovered, separate processes will, by their nature, not have the context of your main Node.js process.正如您所发现的那样,单独的进程就其性质而言,不会具有主 Node.js 进程的上下文。

A couple of solutions are to put that configuration in an include file that can be required in both the main process and in your job's node module, or provide it as part of the job data.一些解决方案是将该配置放在主进程和作业的节点模块中都可能需要的包含文件中,或者将其作为作业数据的一部分提供。

Not all things can be passed in job data for sandboxed workers, as Bull uses child_process.send to pass data back and forth, and it does some serialization and parsing, so be aware of that as well.并不是所有的东西都可以在沙盒工作人员的工作数据中传递,因为 Bull 使用child_process.send来回传递数据,它会进行一些序列化和解析,所以也要注意这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM