Tech Tips

  1. Uncategorized
  2. 71 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!!

Uncategorized recent post

  1. Run Amazon FreeRTOS on M5Stack Core2 for AWS …

  2. Udacity Self-Driving Car Engineer Nanodegree …

  3. Install sbt 1.0.0 and run sample template

  4. Visualization of Neural Network and its Train…

  5. [Machine Learning]Created docker image includ…

関連記事

PAGE TOP