【发布时间】:2016-03-17 12:13:04
【问题描述】:
我对如何正确利用 Node JS 要求有点困惑。
我有一个 Node Webkit 应用程序,它产生子窗口,每个子窗口都需要读取和写入数据到 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 的 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 只在初始程序启动时起作用?
【问题讨论】:
标签: javascript html node.js sqlite require