Search code examples
javascriptnode.jsdirectoryinfinite-looprequire

Why can't I have two .js scripts which execute each other?


I have two .js files: /Desktop/firstFolder/first.js and /Desktop/secondFolder/second.js. I want first to work first, then it executes second. In the end of second I want it to execute first again and so on. Sounds simple, right?

first works fine, then second is doing it's job and then it stops working. Why can't I execute first for the second time?

So first and second scripts are as simple as possible:

console.log('first.js works, launching second.js');
process.chdir('/Users/apple/Desktop/secondFolder');
require('/Users/apple/Desktop/secondFolder/second.js');
console.log('second.js works, launching first.js');
process.chdir('/Users/apple/Desktop/firstFolder');
require('/Users/apple/Desktop/firstFolder/first.js');

Logs from terminal:

first.js works, launching second.js
second.js works, launching first.js
Apples-MacBook-Air:firstFolder apple$ 

Why does it stop working? Does javascript prevent itself from infinite loop? Is there a way to make it happen?

There was a suggested question but it's different because they ask how to make one .js file execute another .js file multiple times instead of two .js files executing each other. What is more, I tried to do the same with my code, I wrap both .js files in module.exports = function() {} and added an extra () at the end of each require but now it throws an error:

  require('/Users/apple/Desktop/firstFolder/first')();
                                                   ^

TypeError: require(...) is not a function


Solution

  • It looks like 'executing the file' just means requiring it, because you don't call any function after requiring it in your code.

    Node doesn't execute a required file twice. Rather, the first time you require a file, it executes the whole file and generates something from your module.exports, and then if you require the same file again, it simply gives you your module.exports again.

    So, what you should do is have your files both export the function that you want to execute, and execute that function in each file.

    Eg in file 2 you have module.exports = function(){...}. And in file 1, you do var file2 = require('./file2'); file2();

    And then do the same thing for executing file1 inside file2.

    And you might then want an entry file that requires file1 and then calls it, var file1 = require('./file1'); file1();