I am very new to JavaScript. And I am trying to execute a .js file which uses jquery to load other scripts with node. My .js file is called test.js
and as follows:
require("jsdom").env("", function(err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
$.getScript("./svmjs/lib/svm.js").done(function(){
console.log("loaded!")
}).fail(function(){
console.log("failed!")
});
})
I am trying to run it on mac with command node test.js
, but I get nothing output in the console. What am I doing wrong here? My impression is that with done
or fail
it will at least output something. But I get nothing. Any ideas?
$.getScript
is used to load in scripts on the browser side. In Node.js you have a better tool: require
.
Just require
your modules directly instead of using jQuery. In fact, it's unlikely you'll need jQuery at all.
Change
$.getScript("./svmjs/lib/svm.js").done(function(){
console.log("loaded!")
}).fail(function(){
console.log("failed!")
});
to
require('./svmjs.lib.svm.js');
jQuery will probably not work in Node.js, as it depends heavily on the browser DOM, which is not present in Node.js (there is no window
object or other code, native to a browser environment only). Also, you do not need jQuery for loading NPM packages.
Instead, you should do something like this:
package.json
if you have not done that already by running npm init
and following the instructions.node-svm
, a Node.js-compatible version of SVM, as a dependency by running npm install --save node-svm
.npm install
to download node-svm
and its dependencies. They will be installed into the node_modules
subdirectory.index.js
or whatever the entry point of your project is (defined in the main
property of package.json
follow this example and you should be good to go.node index.js
and check console output.var svm = require('node-svm');
var xor = [
[[0, 0], 0],
[[0, 1], 1],
[[1, 0], 1],
[[1, 1], 0]
];
// initialize a new predictor
var clf = new svm.CSVC();
clf.train(xor).done(function () {
// predict things
xor.forEach(function(ex){
var prediction = clf.predictSync(ex[0]);
console.log('%d XOR %d => %d', ex[0][0], ex[0][1], prediction);
});
});
0 XOR 0 => 0
0 XOR 1 => 1
1 XOR 0 => 1
1 XOR 1 => 0
I'm assuming that jQuery/$ is undefined
. You need to install it into your project using:
npm install jquery --save
After you do that, add var $ = require('jquery');
to the top of your file.
Also, if you're not working in the browser and using strictly Node then you will need to use require
instead of jQuery's getScript function. getScript is more suited for browser applications.
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.