Using require.js with jsdom for server side rendering - node.js

var html ='<!DOCTYPE html>\n'+
'<html>\n'+
' <head>\n'+
' <meta charset="utf-8" />\n'+
' <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">\n'+
' <title>foobunny rulez!</title>\n'+
' <link rel=\'stylesheet\' href=\'/styles/app.css\' />\n'+
' <script src="http://127.0.0.1:6789/scripts/lib/require.js"></script>\n'+
' </head>\n'+
' <body> \n'+
' <script> \n'+
' document.write("test");\n'+
' require([\'/scripts/config.js\']);\n'+
' require([\'/scripts/main.js\']);\n'+
' </script>\n'+
' </body>\n'+
'</html>';
var jsdom = require("jsdom");
jsdom.defaultDocumentFeatures = {
FetchExternalResources : ['script'],
ProcessExternalResources : ['script'],
MutationEvents : '2.0',
QuerySelector : false
}
var window = jsdom.jsdom(html, null, {
features: {
FetchExternalResources: ["script"],
ProcessExternalResources: ["script"]
}
}).createWindow();
window.addEventListener('load', function(){
setTimeout(function(){
res.send('<html>'+window.document.getElementsByTagName('html')[0].innerHTML)+'</html>';
}, 5000);
});
I have this small bit of code and require does end up adding the script tags to the head
(it adds <script type="text/javascript" charset="utf-8" data-requirecontext="_" data-requiremodule="/scripts/config.js" src="/scripts/config.js"></script>
<script type="text/javascript" charset="utf-8" data-requirecontext="_" data-requiremodule="/scripts/main.js" src="/scripts/main.js"></script>)
But the problem is that it doesn't seem to run any of the code within those scripts (which include more require statements). When the page loads everything runs perfectly, but I am trying to do server side rendering.
Should I be using absolute paths? I tried using http://127.0.0.1:6789/scripts/main.js and same for everything else but it doesn't seem to be working. What could be wrong?

Related

Not able to see image loaded with Phaser 3.24.1

I am just starting to use phaser and the first thing I tried doing is to explore 'hello world' with image project that comes as a demo with installation. I have index.html, phaser.png and phaser.min.js in the same location in a folder. I am running Node.js and started it using npm http-server. When I actually do that, all I see if a black square with size 800x600 and nothing else. The code is like his:
<html>
<head>
<meta charset="UTF-8" />
<title>hello phaser!</title>
<script src="phaser.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function() {
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create });
function preload () {
game.load.image('logo', 'phaser.png');
}
function create () {
var logo = game.add.sprite(game.world.centerX, game.world.centerY, 'logo');
logo.anchor.setTo(0.5, 0.5);
}
};
</script>
</body>
</html>
What is missing here?
You're trying to mix the old style Phaser2 Game constructor while importing Phaser3 so you're callbacks don't work.
See the Phaser3 "Hello World" tutorial here for more working code: https://phaser.io/tutorials/getting-started-phaser3/part5

D3 in vscode webviews, can't see anything

I am trying to do a hello world example with d3 just to see if I can use the library. To this effect I copied this ultraminimialistic example into vscodes webview example.
This gave me the following code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const vscode = require("vscode");
const d3 = require("d3");
function activate(context) {
// Create and show a new webview
const panel = vscode.window.createWebviewPanel('catCoding', // Identifies the type of the webview. Used internally
'Cat Coding', // Title of the panel displayed to the user
vscode.ViewColumn.One, // Editor column to show the new webview panel in.
{} // Webview options. More on these later.
);
panel.webview.html = getWebviewContent();
d3.select(panel.document).append("span").text("Hello, world!");
context.subscriptions.push(vscode.commands.registerCommand('catCoding.start', () => {
}));
}
exports.activate = activate;
function getWebviewContent() {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cat Coding</title>
</head>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
d3.select("body").append("span")
.text("Hello, world!");
</script>
</body>
</html>`;
}
// this method is called when your extension is deactivated
function deactivate() { }
exports.deactivate = deactivate;
//# sourceMappingURL=extension.js.map
My expectation was to see a hello world just like int he example, but I see this instead:
There are no alert messages, the problems, output and debug consoles are all fine and even the chrome dev console reports no errors. I am stuck.
There's 2 different attempts at using d3 in here, they both fail, one uses JS directly, the other uses HTML.

jsdom + canvas on node.js: toDataURL() error

Using canvas#1.2.3 & jsdom#3.1.2 with node v0.12.2, I'm getting an error while trying to use the canvas toDataURL() function.
canvasTest.js:
$(function(){
var canvas = $('<canvas></canvas>').attr({'id':'canvasTest', 'width':'500', 'height':'500'});
var ctx=canvas[0].getContext("2d");
ctx.beginPath();
ctx.arc(100,75,50,0,2*Math.PI);
ctx.stroke();
$('#canvasWrap').append(canvas);
});
HTML Test:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="canvasTest.js"></script>
<script type="text/javascript">
$(function(){
console.log($('body').html());
console.log($('#canvasTest').length);
console.log($('#canvasTest')[0].toDataURL());
})
</script>
</head>
<body>
<div id="canvasWrap"></div>
</body>
</html>
jsdom Test:
var canvas = require('canvas');
var jsdom = require('jsdom');
jsdom.env({
html: '<html><body><div id="canvasWrap"></div></body></html>',
scripts: ['127.0.0.1/jquery-2.1.4.min.js','127.0.0.1/canvasTest.js'],
done:function (err,win) {
var $ = win.jQuery;
$(function(){
console.log($('body').html());
console.log($('#canvasTest').length);
console.log($('#canvasTest')[0].toDataURL());
});
}
});
On my HTML Test in Chrome I get the correct base64-encoded canvas data, while in node.js, the error reads:
TypeError: Cannot read property 'toDataURL' of undefined
You are selecting by ID, so there is no array. Drop the [0] and it should work, or select it another way, with an array:
console.log($('canvas')[0].toDataURL());
or try this:
console.log($('#canvasTest').toDataURL());
or this:
console.log(win.$("#canvasTest").toDataURL());
or this:
console.log(win.document.getElementById("canvasTest").toDataURL());
or this:
console.log(win.document.getElementsByTagName("canvas")[0].toDataURL());

requirejs - i am not getting loaded and "require" function not called

In my simple index file i added the "requirejs" - and calling the define function, but i am not getting any response:
Html :
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script data-main="js/main" src="js/lib/require.js"></script>
</body>
</html>
main.js :
require.config({
baseUrl : "js"
})
require(function () {
alert("hi");
})
I found a solution: and it describes as :
require(["helper/util"], function(util) {
//This function is called when scripts/helper/util.js is loaded.
//If util.js calls define(), then this function is not fired until
//util's dependencies have loaded, and the util argument will hold
//the module value for "helper/util".
});
at here : http://requirejs.org/docs/start.html
thanks for all.

Mocha tests with Yeoman and PhantomJS

I'm using Yeoman to scaffold my project. It comes with several handy things, including a PhantomJS-based test runner.
My problem is that while my tests run correctly in the browser, they time out while trying to run them with PhantomJS in the CLI.
Here's how my test index.html looks like:
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Mocha Spec Runner</title>
<link rel="stylesheet" href="lib/mocha/mocha.css">
</head>
<body>
<div id="mocha"></div>
<script src="lib/mocha/mocha.js"></script>
<!-- assertion framework -->
<script src="lib/chai.js"></script>
<!-- include source files here... -->
<script data-main="scripts/main" src="scripts/vendor/require.js"></script>
<script>
mocha.setup({ui: 'bdd', ignoreLeaks: true});
expect = chai.expect;
should = chai.should();
require(['../spec/map.spec'], function () {
setTimeout(function () {
require(['../runner/mocha']);
}, 100);
});
</script>
</body>
</html>
Here's map.spec.js:
require(['map'], function (Map) {
describe('Choropleth Map Generator', function() {
describe('Configure the map', function () {
it("should enforce mandatory parameters in the configuration", function () {
var config = {title: 'test configuration'};
var map = new Map(config);
(function () {
map.getConfig();
}).should.throw(Error);
});
});
});
});
Now, when I do yeoman test, I get this:
Running "server:phantom" (server) task
Starting static web server on port 3501
[...]
Running "mocha:all" (mocha) task
Testing index.html
<WARN> PhantomJS timed out, possibly due to a missing Mocha run() call. Use --force to continue. </WARN>
Aborted due to warnings.
As I said, yeoman server:test shows my assertions correctly in the browser.
I'm using Yeoman 0.9.6 and PhantomJS 1.7.0. Any help is appreciated.
I solved that same warning by double-checking the path to mocha in test/index.html
<link rel="stylesheet" href="lib/mocha/mocha.css">
</head>
<body>
<div id="mocha"></div>
<script src="lib/mocha/mocha.js"></script>
What is your mocha config In Gruntfile. Do you have something like:
mocha: {
all: ['http://localhost:3501/index.html']
},

Resources