gpt4 book ai didi

javascript - Node 模块。私有(private)变量被重置

转载 作者:太空宇宙 更新时间:2023-11-04 01:06:15 25 4
gpt4 key购买 nike

似乎 Node 模块中的私有(private)变量正在“重置”。例如。我的模块中有以下代码

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();
}
};

我面临的问题是,如果我在 start 之后调用 stop 函数,则 process 变量未定义。

显然,解决这个问题的方法是定义一个对象/类并在模块中公开它。

但现在我很想知道模块在 Node 中是如何工作的。当模块被require时,所有私有(private)变量会发生什么?

编辑

我正在使用 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();

最佳答案

来自 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.

所以你的变量基本上只存在于模块代表的闭包内部。

关于javascript - Node 模块。私有(private)变量被重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22746440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com