masch1na
masch1na

Reputation: 127

JavaScript calling functions in another file

I am aware of import and export, but this doesn't work here because each time you call imported function it starts a new instance of the original file from which it was exported.

I have a JavaScript Code A running in node.js continously without restarting. As it runs, it creates its own data and stores it in arrays.

Please how do I call a function within code A from another file which will run in the same instance Code A is currently running in and that it will respect the stored data in arrays Code A has?

If I use import/export, it calls a function from within Code A, but it doesn't have any stored data in arrays that I gathered whilst running Code A.

Thank you very much.

EDIT: Adding sample code

  1. MAIN FILE
    let calculationArray = []
    
    function add(x, y) {

    if ( calculationArray.includes("abcde") ) {
    
    console.log("Calculation is on timeout", calculationArray)
    
    } 
    
    else {
       calculationArray.push("abcde")
       console.log(x + y)
       return x + y;
    }
    }
      
    module.exports = { add }
    
    
    setInterval(add, 3000, 5, 5)
  1. SECOND FILE WHICH CALLS FUNCTION FROM MAIN FILE and doesn't respect the fact that calculationArray in the original file already has "abcde". It simply starts it own fresh instance with empty array
    const f = require('./calculation.js');
      
      
    f.add(10, 5);

Upvotes: 3

Views: 496

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206028

I'm not sure how you exactly load and call your scripts... so I tried to make something I could reason about of — out of your code.

Using ES6 modules (which use export and import statements), say you have:

  • calculation.js — which adds every second 5+5 to a file-internal array
  • other.js — which imports calculation.js and returns the result of add(100, 100) 200
  • a main index.js which calls:
    • calculations.js the first time after 3500ms
    • other.js after 6500ms

Here are the files and than some explanation on what happens using ES6 dynamic import():

calculation.js

// calculation.js

const calculationArray = [];

const add = (x, y) => {
    const result = x + y;
    calculationArray.push(result);
    console.log(calculationArray.reduce((a, v) => a + v), 0);
    return result;
};

// add 5+5 every 1sec
setInterval(add, 1000, 5, 5);

export { add }

other.js

// other.js

import { add } from "./calculation.js";
// export the result of 100 + 100
export default add(100, 100);

and finally:
index.js

// index.js

const delayedImport_calculation = async () => {
    const { add } = await import("./calculation.js");
    add(10, 5);
};

const delayedImport_other = async () => {
    const { default: otherResult } = await import("./other.js");
    console.log(otherResult);
};

setTimeout(delayedImport_calculation, 3500);
setTimeout(delayedImport_other, 6500);

If you call the main script like: $ node ./index.js from the terminal, you should expect the following console logs:

  1. (Nothing for 3500ms)
  2. 15 after 3500ms since that's when calculation.js was first imported into index.js and called the function add(10, 5);
  3. 25 (after 1sec)
  4. 35 (also after 1sec since the interval inside calculation.js)
  5. 235 since other.js was dynamically imported into index.js and added 100 to the array
  6. other: 200 200 since other.js exports just the result of add(100 + 100)
  7. 245, 255, 265, etc... on intervals of 1sec — all proving the point that the array values are updated as expected.

as you can see above, the .reduce() on the calculationArray returns the expected added values in console.log


Another simpler example (which might be closer to what you have?) with only two files:

  • calculation.js that:
    • every 1sec adds 5+5 to the array
    • exports a default add() function and a getAddResult() method
  • index.js which imports both the default and the helper methods
    • logs every second the sun of the array values using getAddResult()
    • calls add(1000, 1000) after 5sec

calculation.js

const calculationArray = [];

const getAddResult = () => calculationArray.reduce((a, v) => a + v, 0);

const add = (x, y) => {
    const result = x + y;
    calculationArray.push(result);
    return result;
};

// add 5+5 every 100ms
setInterval(add, 100, 5, 5);

export default add
export { getAddResult }

index.js

import add, { getAddResult } from "./calculation.js";

setInterval(() => {
    console.log(getAddResult())
}, 1000);

setTimeout(() => {
    add(1000, 1000);
}, 5000);

the log this time would be approximately like:

  • 90, 180, 280, 370 (in intervals of 1sec)
  • 2470, (after ~5000ms) proving the point that the values in array are updated
  • 2560, 2660, etc... (also in intervals of 1sec)

PS:

for the above to work you either need to use "type": "module" in package.json, or just name all your files extensions as .mjs

Upvotes: 1

Related Questions