Note that there are some explanatory texts on larger screens.

plurals
  1. POSharing & modifying a variable between multiple files node.js
    primarykey
    data
    text
    <h2>main.js</h2> <pre><code>var count = 1; // psuedocode // if (words typed begins with @add) require('./add.js'); // if (words typed begins with @remove) require('./remove.js'); // if (words typed begins with @total) require('./total.js'); module.exports.count = count; </code></pre> <h2>total.js</h2> <pre><code>var count = require('./main.js').count; console.log(count); </code></pre> <h2>add.js</h2> <pre><code>var count = require('./main.js').count; count += 10; console.log(count); </code></pre> <h2>remove.js</h2> <pre><code>var count = require('./main.js').count; count -= 10; console.log(count); </code></pre> <h2>console.log</h2> <pre><code> 1 11 -9 </code></pre> <h2>Background:</h2> <p>I have an application (irc bot), and I want to add a feature that peeps can do @add 1 or @remove 1. I have a main.js that then requires different files depending on the triggers that are said. So add would trigger the add.js file, and that would then require('main.js') and add 10 (10 for simplification, it'll actually parse the number and use that number) to it. The problem I'm having is when someone goes about and does @remove. It require('main.js') and subtracts 10 from 1 resulting in -9. And doing @total would output 1. </p> <p>I've done a fairly good search for module.exports and I haven't come across an example like the one i listed above. <a href="http://nodejs.org/api/modules.html#modules_module_exports" rel="noreferrer">The docs</a> don't include any examples close to what I'm wanting to do; and these questions <a href="https://stackoverflow.com/questions/3922994/share-variables-between-files-in-node-js">1</a>, <a href="https://stackoverflow.com/questions/3919828/share-variables-between-modules-in-javascript-node-js">2</a> I understand--but aren't of any usefulness to me--as I understand what's being said there.</p> <h2>Question:</h2> <p>I'd like to have both @add and @remove manipulate the same variable ( count ), and for @total to return the total of count with the @add and @removes taken into account. Am I using module.exports incorrectly; or is there a common way that variables are shared, with one file being able to modify the contents of the module.exports and returning the results to the main.js file?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload