I installed nodejs and jsdom on my linux server.
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 )
var jsdom = require("jsdom");
var test = require("./libs/nodejstest.js");
jsdom.env({
html: "<div></div>",
done : function (error, window) {
test.randomtest();
}
});
I have also tried loading it via the "scripts" tag for jsdom like this to no avail:
scripts : [" 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. It would have to export randomtest
with something like exports.randomtest = randomtest
.
You said using scripts : ["http://yourjavascript.com/64473118216/nodejstest.js"],
in the configuration does not work, but in fact it does. 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
. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.