2014-02-18 47 views
0

我想用jsdom加载本地javascripts。 现在我想知道如何让jsdom从“__dirname /../ public”加载javascripts。 有人可以帮我吗?Node.js jsdom设置文档根

我当前的代码是:

var fs = require('fs'); 
var jsdom = require('jsdom'); 
jsdom.defaultDocumentFeatures = { 
    FetchExternalResources: ["script"], 
    ProcessExternalResources: ["script"], 
    MutationEvents   : '2.0', 
    QuerySelector   : false 
}; 

exports.test = function(req, res) { 
    var html = fs.readFileSync(__dirname+'/../public/html/lame.html'); 

    var document = jsdom.jsdom(html, null, {documentRoot: __dirname+'/../public/'}); 
    var window = document.createWindow(); 

    window.addEventListener('load', function() { 
     //window.$('script').remove(); 
     //window.$('[id]').removeAttr('id'); 
     res.send(window.document.innerHTML); 
     window.close(); 
    }); 
} 

简单的HTML页面:

<html> 
    <head> 
     <title id="title">bum</title> 
     <script type="text/javascript" src="/javascripts/jquery.min.js"></script> 
     <script type="text/javascript" src="/javascripts/stuff.js"></script> 
    </head> 
    <body> 
     <h1>hello world</h1> 
     <h2 id="bam">XXX</h2> 
    </body> 
</html> 

回答

1

我碰到了同样的问题,得到它的工作。请按以下顺序尝试:

  1. documentRoot没有记录。 documented的选项为url。因此用url代替documentRoot

  2. 如果以上不够,请添加base元素。我已经把我的模板是这样的:

    <head> 
        <base href="@[email protected]"></base> 
        <!-- ... --> 
    </head> 
    

    其中@[email protected]替换为相同的值一个传递给url

上述解决方案是从测试套件中使用的actual code中提取的。