简体   繁体   中英

Can't load a local jquery.js into node.js (NPM jsdom)

I'm trying to load a local jquery.js into node.js NPM jsdom according to the example:

var jsdom = require("jsdom");
var fs = require("fs");
var jquery = fs.readFileSync("c:/test/js/jquery.js", "utf-8"); // here it reads the jquery file from local disk

jsdom.env(
  "http://somewebsite.com",
  [jquery],
  function (err, window) {
    var $ = window.$;
    console.log("HN Links");
    $("td.title:not(:last) a").each(function () {
      console.log(" -", $(this).text());
    });
  }
);

And it is giving the error bellow:

window.$(".detLink")[0].text
       ^

TypeError: window.$ is not a function
    at Object.done (C:\test.js:59:13)
    at C:\nodeJS\node_modules\jsdom\lib\jsdom.js:320:18
    at nextTickCallbackWith0Args (node.js:420:9)
    at process._tickCallback (node.js:349:13)

It only works if I retrieve the jquery from some online CDN:

jsdom.env(
  "http://somewebsite.com",
  ["http://code.jquery.com/jquery.js"], // here it reads the jquery from CDN
  function (err, window) {
    var $ = window.$;
    console.log("HN Links");
    $("td.title:not(:last) a").each(function () {
      console.log(" -", $(this).text());
    });
  }
);

The local jquery is exactly the same from the CDN.

Maybe you should consider using cheerio , which is a "fast, flexible, and lean implementation of core jQuery designed specifically for the server" : https://github.com/cheeriojs/cheerio

Example use case:

return request-promise(options)
    .then( (response) => {
        if (response.statusCode === 200) {
            const $ = cheerio.load(response.body);
            // do something 
        }
    })
    .catch( (err) => { console.log(`Url request error:  ${err}, ${url}`); });

request-promise is an npm package: https://www.npmjs.com/package/request-promise

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM