是否有可能在服务器端使用Node.js使用jQuery选择器/DOM操作?


当前回答

我手动简单地做了,没有任何额外的包或代码。

npm i jquery

然后我复制jquery.min.js文件从node_modules/jquery/dist目录到public/js

<script type='text/javascript' src='/js/jquery.min.js'></script>
<script>
  $(document).ready(function() { console.log( "ready!" ); });
</script>

它会起作用的。测试它

注意,复制/粘贴文件并不是最理想的事情,你可以将文件启用为静态文件,这样expressJS就可以读取它了。但对我来说,把它复制到静态公共目录更容易。

其他回答

在写这篇文章的时候,也有保持的Cheerio。

快速,灵活,精益的实现核心jQuery设计 特别是针对服务器。

模块jsdom是一个很棒的工具。但如果你想评估整个页面,并在服务器端做一些奇怪的事情,我建议在它们自己的上下文中运行它们:

vm.runInContext

所以像require / CommonJS这样的东西不会破坏你的Node进程本身。

你可以在这里找到相关文档。干杯!

jQuery模块可以通过以下方式安装:

npm install jquery

例子:

var $ = require('jquery');
var http = require('http');

var options = {
    host: 'jquery.com',
    port: 80,
    path: '/'
};

var html = '';
http.get(options, function(res) {
res.on('data', function(data) {
    // collect the data chunks to the variable named "html"
    html += data;
}).on('end', function() {
    // the whole of webpage data has been collected. parsing time!
    var title = $(html).find('title').text();
    console.log(title);
 });
});

jQuery在Node.js中的引用**:

http://quaintous.com/2015/07/31/jqery-node-mystery/ http://www.hacksparrow.com/jquery-with-node-js.html

据我所知没有。DOM是一个客户端的东西(jQuery不解析HTML,但解析DOM)。

下面是一些当前的Node.js项目:

https://github.com/ry/node/wiki (https://github.com/nodejs/node)

SimonW的djangode非常酷…

首先,安装它

npm install jquery -S

安装后,您可以如下所示使用它

import $ from 'jquery';
window.jQuery = window.$ = $;
$(selector).hide();

你可以查看我写的完整教程:https://medium.com/fbdevclagos/how-to-use-jquery-on-node-df731bd6abc7