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

标签 javascript node.js

似乎 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/

相关文章:

javascript - 在javascript中淡入淡出

javascript - Extjs 6 ItemSelector 如何以编程方式绘制行

python - 使用 node.js pm2 在虚拟环境中运行 python 脚本

node.js - Sequelize - 嵌套关联查询只检索 1 个数组数据?

node.js - Angular 4 无法加载资源:net::ERR_CONNECTION_REFUSED

node.js - Mongoose 与 MongoDB 验证

javascript - Hello.js 的 Twitter 错误

javascript - 不稳定的 jQuery UI 拖动时可排序

javascript - 播放本地存储的 HTML 格式的 FLV 文件

node.js - 如何修复 'Content Security Policy: The page’ s 设置阻止在 http ://localhost:8080/favicon. ico (“default-src” 处加载资源。'