[英]nodejs executing external function from script
I installed nodejs and jsdom on my linux server. 我在Linux服务器上安装了nodejs和jsdom。
I am trying to do something that should be simple but I cannot find any easy tutorials online for this. 我正在尝试做一些应该很简单的事情,但是我在网上找不到任何简单的教程。
I am simply trying to run a the function "randomtest()" from an external .js file ( http://yourjavascript.com/64473118216/nodejstest.js ) 我只是想从外部.js文件( http://yourjavascript.com/64473118216/nodejstest.js )运行功能“ randomtest()”
var jsdom = require("jsdom");
var test = require("./libs/nodejstest.js");
jsdom.env({
html: "<div></div>",
done : function (error, window) {
test.randomtest();
}
});
It produces following error: 它产生以下错误:
I have also tried loading it via the "scripts" tag for jsdom like this to no avail: 我也尝试通过“脚本”标签为jsdom加载它,但无济于事:
scripts : [" http://yourjavascript.com/64473118216/nodejstest.js "], 脚本:[“ http://yourjavascript.com/64473118216/nodejstest.js ”],
Try this 尝试这个
var jsdom = require("jsdom");
jsdom.env({
html: "<div></div>",
scripts: ["./libs/nodejstest.js"],
done : function (error, window) {
window.randomtest();
}
});
There are a couple issues with what you tried: 您尝试的方法有两个问题:
Loading your nodejstest.js
through Node's require
does not work make the randomtest
function available because nodejstest.js
does not export anything. 通过Node的require
加载nodejstest.js
无法正常工作,因为nodejstest.js
不会导出任何内容 , randomtest
可以使randomtest
函数可用。 It would have to export randomtest
with something like exports.randomtest = randomtest
. 它必须出口randomtest
的东西,如exports.randomtest = randomtest
。
You said using scripts : ["http://yourjavascript.com/64473118216/nodejstest.js"],
in the configuration does not work, but in fact it does. 您说过使用scripts : ["http://yourjavascript.com/64473118216/nodejstest.js"],
在配置中不起作用,但实际上可以。 You do not see the output on the console because the window that JSDOM creates is essentially a new JavaScript virtual environment, and it has its own console
separate from Node's console
. 你不会看到控制台上的输出, 因为JSDOM创建窗口本质上是一个新的JavaScript虚拟环境,它有它自己的console
从节点的单独的console
。 You have to create a bridge between the two, like this: 您必须在两者之间建立桥梁,如下所示:
var jsdom = require("jsdom"); var vc = jsdom.createVirtualConsole(); vc.on("log", function () { console.log.apply(console.log, arguments); }); vc.on("jsdomError", function (er) { throw er; }); jsdom.env({ html: "<div></div>", scripts : ["http://yourjavascript.com/64473118216/nodejstest.js"], virtualConsole: vc, done : function (error, window) { window.randomtest(); } });
With this, the output will show on your console. 这样,输出将显示在您的控制台上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.