2016-08-09 10 views
0

は例に係るNPM jsdomをNode.jsの:のNode.jsにローカルjquery.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()); 
    }); 
    } 
); 

そして、

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

:私はいくつかのオンラインCDNからjQueryのを取得する場合にのみ動作します

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) 

:それは、エラー怒鳴るを与えていますローカルjqueryはCDNとまったく同じです。

答えて

0

たぶん、あなたは「高速で柔軟、そしてサーバーのために特別に設計されたコアのjQueryのリーン実装」である、cheerioの使用を検討してください: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

+0

私は正反対のことをしようとしています。私はオンラインソースからjqueryを取得したくないので、ローカルからロードする必要があります。 – Azevedo

+0

「cheerio」を使用した場合、なぜあなたのニーズは満たされませんか? –

+0

なぜ私は最初にcheerioが必要でしょうか?この質問のポイントは、リモートではなく、jquery ** LOCALLY **をロードすることです。とった? – Azevedo

関連する問題