[英]Node module. Private variables are reset
It seems as if my private variables in a node module are being "reset". 似乎我的节点模块中的私有变量正在“重置”。 Eg I have the following code in a module
例如,我在模块中有以下代码
var exec = require('child_process').exec;
var process;
module.exports.start = function() {
if (!process) {
process = exec('Some process');
}
};
module.exports.stop = function() {
if (process) {
process.kill();
}
};
The problem that I am facing is that process
variable is undefined if I call the stop
function after the start
. 我面临的问题是,如果在
start
之后调用stop
函数,则process
变量是不确定的。
Obviously the fix for this would be to define an object/class and expose that in the module. 显然,解决此问题的方法是定义一个对象/类并将其显示在模块中。
But now I am curious to know how modules work in node. 但是现在我很好奇知道模块如何在节点中工作。 When a module is
require
'd, what happens to all the private variables? 当
require
一个模块时,所有私有变量会怎样?
Edit 编辑
I am using this module from the REPL to test, but an example usage would just be 我正在使用REPL中的此模块进行测试,但示例用法只是
var my_module = require('./my_module');
// the child process starts fine
my_module.start();
// after some time
// but does not end
my_module.stop();
From the node.js
documentation: http://nodejs.org/api/modules.html 从
node.js
文档中: http : //nodejs.org/api/modules.html
Variables local to the module will be private, as though the module was wrapped in a function.
该模块本地的变量将是私有的,就像该模块包装在函数中一样。
So your variable basically exists only inside the clouse represented by the module. 因此,您的变量基本上只存在于模块代表的Clouse内部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.