[英]Call a constructor function from an external .js file in node
我实际上有一个加载几个 js 文件的 html 文件:
<script type="text/javascript" src="jop.js"></script>
<script type="text/javascript" src="script.js"></script>
我的目标是将这两个脚本迁移到 node.js 以独立运行它们(没有浏览器)。
关于js文件:
-jop.js:使用emscripten工具编译,包含构造函数。
-script.js:是程序本身
jop.js 文件内容(起始行):
var PROPModule = function(Module) {
Module = Module || {};
var Module;if(!Module)Module=(typeof PROPModule!=="undefined"?PROPModule:null)||{};var moduleOverrides={};// file continues....
script.js 文件内容(原始开头行):
var PROP = {}; // PROP global object
PROP['preRun'] = prerun; // Will be called before PROP runs, but after the Emscripten runtime has initialized
PROP['onRuntimeInitialized'] = main; // Called when the Emscripten runtime has initialized
PROP['TOTAL_MEMORY'] = 64*1024*1024; // PROP Heap defaults
PROPModule(PROP); // Calling the constructor function with our object
我试图在 script.js 中使用“require”调用构造函数“PROPModule(PROP);”,但没有一种方法有效。 这条路:
script.js(在节点中修改。开始行):
var jopjs = require('./jop.js');
var PROP = {};
PROP['preRun'] = prerun;
PROP['onRuntimeInitialized'] = main;
PROP['TOTAL_MEMORY'] = 64*1024*1024;
jopjs.PROPModule(PROP);
ReferenceError: jopjs is not defined
我对 js 和节点很陌生,我一直在寻找几天没有成功的解决方案。
请有任何建议或想法如何调用此构造函数?
.js 文件在浏览器和 nodejs 中的读取方式不同。 因此,很可能 your.js (为浏览器编码)不会在 nodejs 环境中读取,反之亦然。
为了使我的 js 文件与两者兼容,我所做的是用这个脚本包装我的 js 代码:
/** jop.js */
; (function (window, factory) {
if (typeof exports === 'object') {
module.exports = factory(); // NodeJs Environment
} else {
window.jop = factory(); // Browser Environment
}
}(this, function () {
return (function (window) {
"use string";
let PROPModule = function (Module) {
console.log('PROPModule is called');
}
// exposed functions
return { myFunc };
}(this));
}));
虽然这是在 NodeJS 环境中导入它的方法:
script.js
const jopjs = require('./jop')
虽然这是在浏览器环境中导入它的方法(内部或):
<script type="text/javascript" src="./app/lokidb-seed.js"></script>
<script>
console.log('The "jop" word in window.jop = factory();: ', jop.PROPModule());
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.