Skip to content

Instantly share code, notes, and snippets.

@bingeboy
Created July 26, 2013 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bingeboy/6087474 to your computer and use it in GitHub Desktop.
Save bingeboy/6087474 to your computer and use it in GitHub Desktop.
var http = require('http')
, fs = require('fs')
, request = require('request')
, jsdom = require("jsdom");
//Description: Create a file to pipe to. (this could also be added to a db if recommended.)
request('http://google.com').pipe(fs.createWriteStream('backup.html'))
//Description: use jsdom for DOM scrapping as needed dom needed. Alternatively this could be stored to DB.
jsdom.env({
url: "backup.html",
scripts: ["http://code.jquery.com/jquery.js"],
done: function (errors, window) {
var $ = window.$;
console.log("Data from local file: ");
//will be more specific, just want the body logging for now.
$("body")
console.log("-", $(this).text());
});
}
});
@bingeboy
Copy link
Author

I'm not concerned with the http server method... It's more getting the data from jsdom or an alternative method at this point.

@jasonmcaffee
Copy link

Looking at the docs, instead of passing an object literal to jsdom.env, pass arguments.
First you'll want to get the html contents via fs.readFileSync('dir/backup.html', 'utf-8')

var htmlSource = fs.readFileSync("some/dir/backup.html", "utf8");
jsdom.evn(
    htmlSource,
    ['array', 'of', 'scripts'],
    function(window){

    }
);

@jasonmcaffee
Copy link

Looks like you could also use the object literal config and use the file property.
e.g.

jsdom.env({
   file: '/path/to/backup.html',
   ...

I'm not 100% sure, but it looks like the file might not be populated by the time jsdom is called.
If that's the case, you could remove the use of pipe, and instead use fs.writeFileSync

@bingeboy
Copy link
Author

Thanks Jason I got it working. For now I'm using fs.readFileSync method. I was also missing:

The jsdom.jsdom method.

var jsdom = require("jsdom");

Needed to be:

var jsdom = require("jsdom").jsdom;

This allowed the window callback to load the file. Previously I was getting the file in the error cb.

@bingeboy
Copy link
Author

var fs = require('fs')
  , jsdom = require('jsdom').jsdom;

var htmlSource = fs.readFileSync(__dirname + "/date.html", "utf8")
  , document = jsdom(htmlSource)
  , window = document.parentWindow;

console.log(typeof window.document.getElementsByClassName); //function
console.log(window.document.getElementsByTagName('a')[1].innerHTML); //logs link text "311.json"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment