3

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);
10
  • 1
    because each time you call imported function it starts a new instance of the original file from which it was exported. this is not true and therefore doesn't mean you cannot use import/export, it means you need to change your code. Please post actual code; what exactly are you exporting and how are you calling the function? Commented Aug 17, 2022 at 10:29
  • Hi chris, thanks for reaching out. I added sample code. Run the original file, wait until you get "Calculation is on timeout [ 'abcde' ]" message, then run the second file. Second file shouldn't start, because the calculation in the original file is on timeout (the array includes "abcde"). But it doesn't care and starts new instance with empty array. Commented Aug 17, 2022 at 10:34
  • You're not using ES6 module's export import but rather CommonJS require and module.exports... nodejs.org/api/modules.html Commented Aug 17, 2022 at 10:52
  • If you are running the first file, then run the second file in a new window, then no, it will not allow you to access the first instance's array. Each node instance has its own memory. These are scripts, not databases. They contain instructions for node.exe, they do not magically store information. What you need to do is not require the file but rather communicate with the first instance. You can use for instance node-ipc to do that Commented Aug 17, 2022 at 11:15
  • Are you expecting setInterval(add, 3000, 5, 5); to run before f.add(10, 5);??? Or are you expecting that every place that imports a file should be the same instance of that file? Commented Aug 17, 2022 at 12:54

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for your answer. So far that I tried it, unfortunately, it doesn't seem to work. The whole point is that the original file contains an array which if includes a specific value, in this example "abcde", the calculation triggered from the second file should NOT happen, because "abcde" is present in the array of the original file. The only reason for setInterval is to trigger one calculation in the original file and then just keep saying "Calculation on timeout" and that should also prevent second file from performing any calculations.
OP has two node processes and for some reason expects the second thread to have access to the first one's array. This won't work regardless of how stuff is imported/required/etc. OP needs to store the array externally to the script so both processes can access the same storage space.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.