为什么我不能有两个相互执行的 .js 脚本?

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

我有两个 .js 文件:/Desktop/firstFolder/first.js/Desktop/secondFolder/second.js。 我想让 first 先工作,然后它执行 second。在 second 结束时我希望它再次执行 first 等等。听起来很简单吧?

first 工作正常,然后 second 正在做它的工作,然后停止工作。为什么我第二次执行不了first

因此firstsecond脚本尽可能简单:

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');

来自终端的日志:

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

为什么它停止工作? javascript 是否防止自己陷入死循环?有办法实现吗?

有一个 但它是不同的,因为他们询问如何让一个 .js 文件多次执行另一个 .js 文件,而不是两个 .js 文件相互执行。更重要的是,我尝试对我的代码做同样的事情,我将两个 .js 文件都包装在 module.exports = function() {} 中并在每个 require 的末尾添加了一个额外的 () 但现在它抛出一个错误:

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

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

Node模块系统是为模块构建的,这意味着require的语义是“要求”,而不是“执行”。两个模块在逻辑上不能仅仅为了存在而相互依赖,但它们的导出可以,所以这就是 Node 为您提供的递归行为 require:您获取已经存在的模块的导出对象的当前值运行宁.

所以改为从模块中导出您的功能:

const second = require('/Users/apple/Desktop/secondFolder/second.js');

exports.run = () => {
    console.log('first.js works, launching second.js');
    process.chdir('/Users/apple/Desktop/secondFolder');
    second.run();
};
const first = require('/Users/apple/Desktop/firstFolder/first.js');

exports.run = () => {
    console.log('second.js works, launching first.js');
    process.chdir('/Users/apple/Desktop/firstFolder');
    first.run();
};

这应该会引发堆栈溢出错误。 (如果您不想出现堆栈溢出错误,请将 运行 调用替换为不保留堆栈的内容,例如 process.nextTick(first.run)。)

看起来'executing the file'只是意味着要求它,因为你在代码中要求它之后没有调用任何函数。

节点没有执行所需文件两次。相反,当你第一次需要一个文件时,它会执行整个文件并从你的 module.exports 中生成一些东西,然后如果你再次需要同一个文件,它只会再次给你你的 module.exports

所以,您应该做的是让您的文件既导出您要执行的功能,又在每个文件中执行该功能。

例如,在文件 2 中您有 module.exports = function(){...}。在文件 1 中,您执行 var file2 = require('./file2'); file2();

然后做同样的事情,在 file2 中执行 file1。

然后您可能想要一个需要 file1 的入口文件,然后调用它,var file1 = require('./file1'); file1();

JS 文件一旦通过 nodejs 中的 require() 调用就会存储在缓存中,因此控制台只会被调用一次,当两个文件都被加载时,它会等待事件发生或其他函数执行。

您可以在 https://nodejs.org/api/modules.html#modules_require_id

中阅读更多内容

如果你想永远循环使用 for、foreach、while 之一。