簡體   English   中英

無法將本地jquery.js加載到node.js(NPM jsdom)

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

我正在根據示例嘗試將本地jquery.js加載到node.js NPM jsdom中

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());
    });
  }
);

它給出了以下錯誤:

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)

僅當我從某些在線CDN檢索jquery時,它才有效:

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());
    });
  }
);

本地jquery與CDN完全相同。

也許您應該考慮使用cheerio ,它是“專門為服務器設計的jQuery核心的快速,靈活和精益實現”: https : //github.com/cheeriojs/cheerio

用例示例:

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是一個npm軟件包: https ://www.npmjs.com/package/request-promise

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM