简体   繁体   中英

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 .

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?

Edit

I am using this module from the REPL to test, but an example usage would just be

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

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.

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