0

I'm trying to find a way to execute the following steps.

  • Write Node.js code for the browser
  • Compile the code with browserify
  • Test the browser code in the terminal

I would love to get the console.logs that the browser receives, but within the terminal. This would not only save me time (from creating a HTML file, running a server, opening a browser), it would also allow for cool things like automatic testing before deployment.

I'm trying to make something called headless-test.js a phantomjs script that would get passed an argument using system.args[1] and fs.read can get the contents of any javascript you pass to it.

var content = fs.read(system.args[1])
page.content = '<html><body><script type="text/javascript">'+content+'</script></body></html>'

That would allow me to do something like this:

phantomjs ./headless-test.js ./bundle.js

I was getting this error SyntaxError: Multiline comment was not closed properly so make sure you uglify your bundle.js.

All of this would be amazing and work if I could get this demo below working. The minimal viable product:

var system = require("system")
var webPage = require('webpage')
var page = require('webpage').create()
page.content = '<html><body><script type="text/javascript">console.log("hello world")</script></body></html>';

page.onConsoleMessage = function(msg, lineNum, sourceId) {
  console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};

page.evaluate(function(){

})

phantom.exit();

The expected results here are:

$ phantomjs ./headless-test.js
hello world

However I'm getting no stdout from phantom.

ThomasReggi
  • 55,053
  • 85
  • 237
  • 424

3 Answers3

1

If you assign something to page.content it is immediately evaluated, but you register to the console.log() from page context after that. You simply miss the console.log() from the script element in the page.

Move the page.content assignment after the page.onConsoleMessage function.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
0
var system = require("system")
var webPage = require('webpage')
var page = require('webpage').create()

page.onConsoleMessage = function(msg, lineNum, sourceId) {
  console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
}

var fs = require("fs")
var content = fs.read(system.args[1])
page.content = '<html><body><script type="text/javascript">'+content+'</script></body></html>'

phantom.exit();
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
0

I made a node tool for this: https://github.com/mantoni/phantomic

If you should also want to use Mocha as a test framework, try Mochify (https://github.com/mantoni/mochify.js). It uses phantomic with brout to get the console output into the terminal properly.

mantoni
  • 1,612
  • 11
  • 10