是否可以使用Node.js在服务器端使用jQuery选择器/ DOM操作?
是否可以使用Node.js在服务器端使用jQuery选择器/ DOM操作?
Answers:
更新(18-Jun-18):似乎有一个重大更新jsdom
,导致原来的答案不再起作用。我找到了这个答案,解释了如何使用jsdom
现在。我已经在下面复制了相关代码。
var jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = (new JSDOM('')).window;
global.document = document;
var $ = jQuery = require('jquery')(window);
注意:原始答案没有提及您还需要使用安装jsdomnpm install jsdom
更新(2013年末):官方jQuery团队终于jquery
在npm上接管了该软件包的管理:
npm install jquery
然后:
require("jsdom").env("", function (err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
});
require("...").env is not a function
。
TypeError: require(...).env is not a function
是的,可以使用我创建的名为nodeQuery的库
var Express = require('express')
, dnode = require('dnode')
, nQuery = require('nodeQuery')
, express = Express.createServer();
var app = function ($) {
$.on('ready', function () {
// do some stuff to the dom in real-time
$('body').append('Hello World');
$('body').append('<input type="text" />');
$('input').live('click', function () {
console.log('input clicked');
// ...
});
});
};
nQuery
.use(app);
express
.use(nQuery.middleware)
.use(Express.static(__dirname + '/public'))
.listen(3000);
dnode(nQuery.middleware).listen(express);
, express = Express.createServer();
与TypeError: Express.createServer is not a function
任何想法?
npm install --save express
在命令提示符下尝试。
现在,您可以使用jsdom。只需在示例目录中查看其jquery示例即可。
这是我在Node.js中创建简单爬网程序的公式。这是想要在服务器端进行DOM操作的主要原因,这也许就是您来到这里的原因。
首先,用于request
下载要解析的页面。下载完成后,cheerio
像使用jQuery一样处理它并开始DOM操作。
工作示例:
var
request = require('request'),
cheerio = require('cheerio');
function parse(url) {
request(url, function (error, response, body) {
var
$ = cheerio.load(body);
$('.question-summary .question-hyperlink').each(function () {
console.info($(this).text());
});
})
}
parse('http://stackoverflow.com/');
此示例将在控制台上显示SO主页上显示的所有最重要的问题。这就是为什么我喜欢Node.js及其社区。没有比这更容易的了:-)
安装依赖项:
npm安装请求cheerio
并运行(假设上面的脚本在file中crawler.js
):
节点crawler.js
某些页面会以某种编码包含非英语内容,您需要将其解码为UTF-8
。例如,巴西葡萄牙语(或拉丁语来源的任何其他语言)的页面很可能会以ISO-8859-1
(aka“ latin1”)编码。当需要解码时,我告诉我request
不要以任何方式解释内容,而是使用它iconv-lite
来完成工作。
工作示例:
var
request = require('request'),
iconv = require('iconv-lite'),
cheerio = require('cheerio');
var
PAGE_ENCODING = 'utf-8'; // change to match page encoding
function parse(url) {
request({
url: url,
encoding: null // do not interpret content yet
}, function (error, response, body) {
var
$ = cheerio.load(iconv.decode(body, PAGE_ENCODING));
$('.question-summary .question-hyperlink').each(function () {
console.info($(this).text());
});
})
}
parse('http://stackoverflow.com/');
在运行之前,请安装依赖项:
npm安装请求iconv-lite cheerio
最后:
节点crawler.js
下一步将是链接。假设您要列出SO每个最重要问题的所有发帖人。您必须首先列出所有热门问题(上面的示例),然后输入每个链接,解析每个问题的页面以获取涉及的用户列表。
当您开始关注链接时,回调地狱就可以开始。为了避免这种情况,您应该使用某种承诺,期货或其他任何方式。我总是在工具带中保持异步。因此,这是使用异步的搜寻器的完整示例:
var
url = require('url'),
request = require('request'),
async = require('async'),
cheerio = require('cheerio');
var
baseUrl = 'http://stackoverflow.com/';
// Gets a page and returns a callback with a $ object
function getPage(url, parseFn) {
request({
url: url
}, function (error, response, body) {
parseFn(cheerio.load(body))
});
}
getPage(baseUrl, function ($) {
var
questions;
// Get list of questions
questions = $('.question-summary .question-hyperlink').map(function () {
return {
title: $(this).text(),
url: url.resolve(baseUrl, $(this).attr('href'))
};
}).get().slice(0, 5); // limit to the top 5 questions
// For each question
async.map(questions, function (question, questionDone) {
getPage(question.url, function ($$) {
// Get list of users
question.users = $$('.post-signature .user-details a').map(function () {
return $$(this).text();
}).get();
questionDone(null, question);
});
}, function (err, questionsWithPosters) {
// This function is called by async when all questions have been parsed
questionsWithPosters.forEach(function (question) {
// Prints each question along with its user list
console.info(question.title);
question.users.forEach(function (user) {
console.info('\t%s', user);
});
});
});
});
运行之前:
npm安装请求异步cheerio
运行测试:
节点crawler.js
样本输出:
Is it possible to pause a Docker image build?
conradk
Thomasleveil
PHP Image Crop Issue
Elyor
Houston Molinar
Add two object in rails
user1670773
Makoto
max
Asymmetric encryption discrepancy - Android vs Java
Cookie Monster
Wand Maker
Objective-C: Adding 10 seconds to timer in SpriteKit
Christian K Rider
这就是您开始制作自己的搜寻器的基本知识:-)
在2016年,事情变得更加轻松。使用控制台将jquery安装到node.js:
npm install jquery
将其绑定到$
您的node.js代码中的变量(例如-我已经习惯了):
var $ = require("jquery");
做东西:
$.ajax({
url: 'gimme_json.php',
dataType: 'json',
method: 'GET',
data: { "now" : true }
});
由于它基于node.js,因此也适用于gulp。
var $ = require("jquery"); $.ajax // undefined
(目前暂不支持投票)。
npm install jquery
先做过吗?
> console.log(require("jquery").toString());
给了我工厂功能:function ( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }
我不得不在jsdom中使用上面的答案: stackoverflow.com/a/4129032/539490
我相信现在的答案是肯定的。
https://github.com/tmpvar/jsdom
var navigator = { userAgent: "node-js" };
var jQuery = require("./node-jquery").jQueryInit(window, navigator);
npm install jquery --save
#note所有小写
npm install jsdom --save
const jsdom = require("jsdom");
const dom = new jsdom.JSDOM(`<!DOCTYPE html>`);
var $ = require("jquery")(dom.window);
$.getJSON('https://api.github.com/users/nhambayi',function(data) {
console.log(data);
});
可以使用以下方法安装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);
});
});
Node.js **中的jQuery引用:
您必须使用新的JSDOM API来获取窗口。
const jsdom = require("jsdom");
const { window } = new jsdom.JSDOM(`...`);
var $ = require("jquery")(window);
...
为了支持HTML5 ,.JSDOM()应该为.JSDOM(“ <!DOCTYPE html>”)吗?
警告
正如Golo Roden所提到的,这种解决方案是不正确的。这只是一个快速的解决方案,可以帮助人们使用Node应用程序结构运行其实际的jQuery代码,但这不是Node的原理,因为jQuery仍在客户端而不是服务器端运行。很抱歉给您一个错误的答案。
您也可以使用node渲染Jade并将jQuery代码放入其中。这是玉文件的代码:
!!! 5
html(lang="en")
head
title Holamundo!
script(type='text/javascript', src='http://code.jquery.com/jquery-1.9.1.js')
body
h1#headTitle Hello, World
p#content This is an example of Jade.
script
$('#headTitle').click(function() {
$(this).hide();
});
$('#content').click(function() {
$(this).hide();
});
从jsdom v10开始,不推荐使用.env()函数。在尝试了很多需要jquery的事情之后,我像下面那样做:
var jsdom = require('jsdom');
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = (new JSDOM('')).window;
global.document = document;
var $ = jQuery = require('jquery')(window);
希望这对您或遇到此类问题的任何人有帮助。
TypeError: JSDOM is not a constructor
$.each
。我只添加了这些行,然后按如下所示进行操作: $.each(errors, function (ind,error) { res.send(error.msg);console.log(error.msg); });
希望这会有所帮助!
首先安装
npm install jquery -S
安装后,可以按以下方式使用
import $ from 'jquery';
window.jQuery = window.$ = $;
$(selector).hide();
您可以查看我在这里编写的完整教程:https : //medium.com/fbdevclagos/how-to-use-jquery-on-node-df731bd6abc7
这些解决方案都没有对我的Electron App有所帮助。
我的解决方案(解决方法):
npm install jquery
在您的index.js
文件中:
var jQuery = $ = require('jquery');
通过.js
以下方式在文件中编写您的jQuery函数:
jQuery(document).ready(function() {
是的,jQuery
可以用于Node.js
。
在节点项目中包括jQuery的步骤:-
npm i jquery --save
在代码中包含jQuery
import jQuery from 'jquery';
const $ = jQuery;
我确实一直在node.js项目中使用jquery,特别是在chrome扩展的项目中。
例如https://github.com/fxnoob/gesture-control-chrome-extension/blob/master/src/default_plugins/tab.js
否。将浏览器环境移植到节点将是一项巨大的工作。
我正在研究单元测试的另一种方法是创建jQuery的“模拟”版本,该版本在调用选择器时提供回调。
这样,您就可以在没有DOM的情况下对jQuery插件进行单元测试。您仍然必须在真实的浏览器中进行测试,以查看代码是否可以正常运行,但是,如果您发现浏览器特定的问题,则也可以轻松地“模拟”单元测试中的问题。
准备好显示后,我将其推送到github.com/felixge。
从来没听说过。DOM是客户端的东西(jQuery不会解析HTML,而是DOM)。
以下是一些当前的Node.js项目:
https://github.com/ry/node/wiki(https://github.com/nodejs/node)
而且SimonW的djangode非常酷...
一种替代方法是使用Underscore.js。它应该提供您可能希望从JQuery的服务器端获得的东西。