Trying to understand jsdom and perhaps node.js generally...

67 views
Skip to first unread message

Spencer Parkin

unread,
Jun 16, 2016, 8:41:45 PM6/16/16
to jsdom
Here is the chunk of code for this discussion...

var ServerCallback = function( request, result )
{
var urlData = url.parse( request.url );

if( urlData.pathname === '/' )
{
var htmlPage = fs.readFileSync( 'CheckersLobby.html', 'utf8' );

var JsdomCallback = function( errors, window )
{
var $ = window.$;

$( 'h1' ).text( 'Blah!' );

htmlPage = window.document.documentElement.outerHTML;

result.writeHead( 200, { 'Content-type' : 'text/html' } );
result.end( htmlPage );
}

// Note that the following call returns before the given callback is called, so we
// return from this callback without responding to the request.  However, the
// callback eventually gets called and is still able to respond to the request.
// I'm not sure exactly what is going on here, or why this works.
jsdom.env( htmlPage, [ 'http://code.jquery.com/jquery.js' ], JsdomCallback );
}
else
{
result.writeHead( 404, { 'Content-Type' : 'text/plain' } );
result.end( 'Page not found!\n' );
}
}

var server = http.createServer( ServerCallback );

Of course, this is only a fragment of my entire server-side program.  Note the comment in green above.  For the longest time, I was trying to use the side-effects of the "JsdomCallback" function right after the call "jsdom.env(...)".  But that didn't work, because the callback is not called before the "jsdom.env(...)" call returns.  I would have expected, however, it mandatory that I respond to the request before the "ServerCallback" function returns.  What exactly is going on here?  Why does this all work?  Is there some logic/magic in Node.js that I'm not realizing here?  Certainly when the "jsdom.env(...)" call is made, it has to store the "JsdomCallback" somewhere so that it can be called later.  Does the "jsdom" module stuff the callback into Node's async-callback queue or something?  And it gets called after an HTTP request is made for the jQuery file?  And by the way, is Node's message pump implicit?  Can it optionally be implemented explicitly?

I'm totally new to Javascript, Node.js, and jQuery.  Thanks for any enlightenment you may be able to provide me.
Reply all
Reply to author
Forward
0 new messages