Node JS 需要最初只工作(调试)

Node JS Require Works Initially Only (debugging)

我对如何正确使用 Node JS 要求有点困惑。

我有一个生成子 windows 的 Node Webkit 应用程序,每个子 window 都需要读取数据并将数据写入 sqlite3 数据库。

在我的 index.html 中,我有一个创建 iframe 的按钮

<!DOCTYPE html>
<html>
<head>
<script src="index.js"></script>
</head>

<script>
   var sqlite3 = require('sqlite3').verbose();
   console.log(sqlite3);
</script>

<body>

   <!-- CREATE NEW APP IF NEEDED -->
   <button onclick="spawnApp()">Spawn App</button>

   <div id="containApp">

      <!-- RUN INITIAL APP -->
      <iframe src="apps/sub.html"></iframe>

   </div>

</body>
</html>

spawnApp() 是 index.js 文件中的一个函数

function spawnApp() {

   var varIframe = document.createElement("iframe");
   varIframe.src = "apps/sub.html";

   var varContainer = document.getElementById("containApp");
   varContainer.appendChild(varIframe);

}

它生成的应用程序称为 sub.html,需要它来建立与 sqlite3 的数据库连接

<!DOCTYPE html>
<html>

<script>
   var sqlite3 = require('sqlite3').verbose();
   console.log(sqlite3);
</script>

<body>

   <h4>Sub App</h4>

</body>
</html>

当我第一次执行该程序时,它似乎运行良好,因为我在控制台中得到以下输出。

> Object                                                   index.html:9
> Object                                                     sub.html:6

这是我所期望的,一个对象是根据 index.html 上的 require 创建的,然后是初始的 sub.html,这是一个静态写入 index.html.[=16 的 iframe =]

但是我点击按钮添加一个新的应用程序我得到以下错误

> Object                                                   index.html:9
> Object                                                     sub.html:6
> Uncaught ReferenceError: require is not defined            sub.html:5

奇怪的是,如果我点击刷新按钮,甚至没有使用该按钮创建新应用程序,我也会收到类似的错误。

> Object {...}                                             index.html:9
> Uncaught ReferenceError: require is not defined            sub.html:5

我不知道是什么原因造成的,我花了很多时间试图弄明白,为什么 require 只在初始程序启动时起作用?

我相信我已经找到了这个问题的原因和解决方法。

我正在阅读一些 Node 问答论坛,似乎 Node 实际上并不支持 iframe,因此在调用 node 模块时会出现一些意外行为。

虽然解决方法(可能不适合每个人的需要)只是简单地使用 div 代替并使用一些 jQuery/Javascript 将 sub.html 中的元素写入 div 代替。

不是很好的解决方法,但我正在研究 HTML 生成器以显着加快 HTML 内容的生成速度,这将使解决方法更有效。