Access logs from console.log() in Node.js vm module
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(); }
});
Maybe it's better so just forward the current console to the newly created context object:
let contextObj = {
console: console
};