3

Say I have two files, index.js & test.js.

Now they contain the following code;

index.js

var test = require('./test');

test.execute();

function execute(){
  console.log('Execute this from the test file');
}

module.exports = {
  execute
}

test.js

var index = require('./index'); 

index.execute();

function execute(){
  console.log('Execute this from the index file');
}

module.exports = {
  execute
}

They're both pretty much the same thing, all they are doing is executing the opponents execute() function. However, when I start node I run node index to start the server. Now what happens is the execute() function of the test.js file becomes non-existent as the test module is required before the execute function with index.js is exported.

What is a good solution to work around this issue?

Borda
  • 139
  • 1
  • 10

1 Answers1

0

It seems in this exact case you can just up the export assigning to the top:

index.js

module.exports = {
  execute
}

var test = require('./test');

test.execute();

function execute(){
  console.log('Execute this from the test file');
}

test.js

module.exports = {
  execute
}

var index = require('./index'); 

index.execute();

function execute(){
  console.log('Execute this from the index file');
}
vsemozhebuty
  • 12,992
  • 1
  • 26
  • 26