0

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

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. 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.

Any help to fix this error would be greatly appreciated. Thank you very much!

caliHI
  • 37
  • 5

2 Answers2

3

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.

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.

Community
  • 1
  • 1
apkostka
  • 405
  • 3
  • 13
0
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). Thank you!

caliHI
  • 37
  • 5