简体   繁体   English

通过命令行在无浏览器的jQuery中使用node.js

[英]Using node.js with browserless jQuery via the command line

I am trying to run this script below via the command line 我正在尝试通过命令行在下面运行此脚本

var argv = require('optimist').argv,
$ = require('jquery'),
fs = require('fs');
var file = argv._[0];
var html = fs.readFileSync(file, 'UTF-8');
$(html).find('p').each(function(index) {
var content = $(this).html();
console.log('Paragraph ' + (index + 1) + ': ' + content);
}); //script.js

The command is $ node script.js page.html where page.html is the argument 命令是$ node script.js page.html ,其中page.html是参数

The error I get is: 我得到的错误是:

./node_modules/jquery/dist/jquery.js:29
                throw new Error( "jQuery requires a window with a document" );
Error: jQuery requires a window with a document
at module.exports (./node_modules/jquery/dist/jquery.js:29:12)
...

I am using jquery-2.1.3. 我正在使用jquery-2.1.3。 I know that this used to work, once upon a time, but it looks like something has changed. 我知道这曾经曾经起作用过,但是看起来有些变化。

Also I did follow the instructions at http://rkulla.blogspot.com/2014/04/using-browserify-with-jquery-backbonejs.html but I am still getting the same error. 另外,我确实按照http://rkulla.blogspot.com/2014/04/using-browserify-with-jquery-backbonejs.html上的说明进行操作,但是我仍然遇到相同的错误。

Any help to fix this error would be greatly appreciated. 修复此错误的任何帮助将不胜感激。 Thank you very much! 非常感谢你!

See this answer . 看到这个答案 The npm package for jQuery no longer includes jsdom , which provides the DOM environment needed to work with jQuery on the server. jQuery的npm软件包不再包含jsdom ,它提供了在服务器上使用jQuery所需的DOM环境。

On the other hand, you could just use cheerio , an implementation of jQuery for the server, to parse the html and use jQuery's selectors. 另一方面,您可以只使用cheerio (服务器的jQuery实现)来解析html并使用jQuery的选择器。

var argv = require('optimist').argv,
$ = require('cheerio'),
fs = require('fs');

var file = argv._[0];
...

I could not install jsdom for the life of me so I gave up on that, but cheerio ( npm install worked very smoothly after editing package.json ) solved the problem (see code modification above). 我一生都无法安装jsdom ,所以我放弃了,但是cheerio (编辑package.jsonnpm install运行非常顺利)解决了这个问题(请参见上面的代码修改)。 Thank you! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM