简体   繁体   中英

Nodejs global variable not working in separate process

I am using queues with bullJS library. In entry point, I have defined global.db variable which I can use everywhere.

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.

As you've discovered, separate processes will, by their nature, not have the context of your main Node.js process.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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