Access Logs From Console.log() In Node.js Vm Module


Answer :

You can just wrap console.log directly:

function hook_consolelog(callback) {     var old_log = console.log;      console.log = (function(write) {         return function() {             write.apply(console, arguments)             callback.apply(null, arguments);         }     })(console.log)      return function() {         console.log = old_log;     } }  var result; var unhook = hook_consolelog(function(v) {     result = v; });  console.log('hello'); unhook(); console.log('goodbye'); console.log('the result is ', result);​ 

Since console.log simply calls process.stdout, another approach would be to capture the stdout events using a bit of wrapper magic like this:

var util = require('util')  function hook_stdout(callback) {     var old_write = process.stdout.write      process.stdout.write = (function(write) {         return function(string, encoding, fd) {             write.apply(process.stdout, arguments)             callback(string, encoding, fd)         }     })(process.stdout.write)      return function() {         process.stdout.write = old_write     } }  var unhook = hook_stdout(function(string, encoding, fd) {     util.debug('stdout: ' + util.inspect(string))     if( string == 'foobar' ) { unhook(); } }); 

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable