简体   繁体   English

在节点进程中共享变量的最佳方式

[英]Best way to share variables in node processes

Suppose I have 2 two processes like these:假设我有两个这样的过程:

file1.js文件1.js

let variable1 = "variable1"

file2.js文件2.js

let variable2 = "variable2"

that have both been spawned using都使用

node file1.js
node file2.js

Is there a way to let them communicate?有没有办法让他们交流? For example can I get variable1 's value from file2.js ?例如,我可以从file2.js获取variable1的值吗?

If you create a master node js and fork 2 child node js process than you can communicate data between parent and child .如果您创建一个主节点 js 并fork 2 个子节点 js 进程,那么您可以在parent and child之间进行数据通信。

Basic example:基本示例:

const fork = require('child_process').fork;

const program = path.resolve('child.js');
const parameters = [];
const options = {
  stdio: [ 'pipe', 'pipe', 'pipe', 'ipc' ]
};

const child = fork(program, parameters, options);
child.on('message', message => {
  console.log('message from child:', message);
  child.send('Hi');
});

More: https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options更多: https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options

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

相关问题 如何保留共享节点集群中所有节点进程的变量? - how to keep variables that share all node processes in node cluster? 跨程序/线程共享变量的最佳方法? - Best way to share variables across programs/threads? webpack/babel:在包之间共享变量的最佳方式是什么? - webpack/babel : what is the best way to share variables between bundles? 组织后端(节点)进程和使用这些进程一部分的前端(Vue / Nuxt)的最佳方法 - Best way to organise back end (Node) processes and front end (Vue / Nuxt) that uses part of these processes 在node.js和django之间共享数据的最佳方式? - Best way to share data between node.js and django? 有没有办法在两个javascript节点运行之间共享和编辑全局变量? - Is there a way to share and edit global variables between two javascript node runs? 将变量传递给Node.js中的回调函数的最佳方法 - Best way to pass variables into callback functions in Node.js 如何在 Node 中共享 scope 和变量? - How to share scope and variables in Node? 使用Google Closure编译器时,在浏览器和node.js之间共享JS的最佳方法 - Best way to share JS between browser and node.js when using Google Closure compiler 什么被认为是在节点模块内共享“全局”变量的好方法? - What's considered a good way to share “global” variables inside a node module?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM