Android console.log crashes in CommonJS module

You must Login before you can answer or comment on any questions.

I am trying to use Javascript code originally designed for a NodeJS environment in Titanium. They make use of the console.log method, which was introduced in Titanium SDK 2.1.0 to make porting from other environments easier. On iPhone, console.log works fine. It also kind of works on Android, but only when called from app.js or a file included from app.js via Titanium.include. It never works on Android from within a CommonJS module file. I always get the following error: "Uncaught ReferenceError: console is not defined."

For example:

app.js:

console.log('inside app.js');
Ti.include('include.js');
require('require');
include.js:
console.log('inside include.js');
require.js:
console.log('inside require.js');
On iPhone, all three messages are logged. However, on Android, only the first two ("inside app.js" and "inside include.js") are logged and it crashes on the first line of require.js: console.log('inside require.js');

Any suggestions would be appreciated. I know that I could use Titanium.API.log instead, but that is not very attractive as it would require a giant find and replace and console.log is supposed to work!

  • Application type: mobile
  • Titanium SDK: 2.1.1 (07/27/12 14:01 0fd84a2)
  • Platform and version: Android 2.2
  • Device: Android emulator
  • Host Operating System: OSX 10.7.4
  • Titanium Studio: 2.1.1.201207271312

1 Answer

Probably a Bug, you could work around

console = console || {};
console.log = console.log || function(s) { Ti.API.info(s);
or some thing similar

— answered 9 months ago by Alexander Bauer
answer permalink
4 Comments
  • missing }

    — commented 9 months ago by Alexander Bauer

  • That would certainly work, however, Android does not allow true global variables; each CommonJS module is given its own separate execution context (see this question). That would require placing the code you provided into a new console.js file and adding var console = require('console'); to the top of each and every file. Again, that would work, but I would rather use a better solution, if it exists (which it might not). Maybe I should just wait and hope this will be fixed in an upcoming SDK update.

    — commented 9 months ago by Coding Monkey

  • I know that but as Long as the Bug exist thats the only way. You could try to prototype it, so each module inherits it.

    — commented 9 months ago by Alexander Bauer

  • Show 1 more comment

Your Answer

Think you can help? Login to answer this question!