プログラミング + アカデミック + 何か面白いこと

  1. Programming
  2. 340 view

[Javascript][node.js]Try to use jsdom

I tried to run ember.js on node.js.
But I couldn’t get node.js, so I made something different compared with original motivation.

To use jquery on node.js jsdom and domToHtml are needed.
Using them, I wrote code that appends p element in body element using jquery.

var http = require("http");
var url = require("url");
var fs = require('fs');
var jsdom = require('jsdom');
var path = require('path');
var jsdomHome = path.dirname(require.resolve('jsdom'));
var domToHtml = require(path.resolve(jsdomHome, 'jsdom/browser/domtohtml'));

var jquery = 'http://code.jquery.com/jquery-1.10.1.min.js';

function start() {
    function onRequest(request, response) {
        var pathname = url.parse(request.url).pathname;
        console.log("Request for " + pathname + " received.");

        var content = fs.readFileSync("./index.html", 'utf-8')
        var document = jsdom.jsdom(content);
        var window = document.createWindow();

        jsdom.jQueryify(window, jquery, function(window, $) {
            $('body').append('<div>More Hello world!!</div>');
            response.writeHead(200, {"Contet-Type": "text/plain"});
            response.write(domToHtml.domToHtml(document, true));
            response.end();
        });
    }
    http.createServer(onRequest).listen(8080);
    console.log("Server has started.");
}

start();

html file which used as content is following.

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>EmberJS Test</title>
    </head>
    <body>
        <div>Hello, world!</div>
    </body>
</html>

The result is following.

Hello, world!
More Hello world!!

Programming recent post

  1. Install sbt 1.0.0 and run sample template

  2. [Machine Learning]Created docker image includ…

  3. [Node.js]How to write batch script with Node.…

  4. [Play][Scala]Develop Request Driven Batch Usi…

  5. [OpenCV][Ruby]Auto check web page design corr…

関連記事

PAGE TOP