找到你要的答案

Q:Listen for message written to console node.js

Q:听消息写入控制台Node.js

Is there a good way of setting up an event in node to watch for when something is written to the console? I would like something like watches the console and reacts accordingly if a particular message was written to it. Is there a better way to do that besides create a function that wraps console.log and the wrapper function performs the action I need? is there anything better than this? This isn't all that feasible, and it'd be much easier to just listen for an onConsole event

function logWrapper(msg,fn){
   console.log(msg)
   fn();
}

Is there a good way of setting up an event in node to watch for when something is written to the console? I would like something like watches the console and reacts accordingly if a particular message was written to it. Is there a better way to do that besides create a function that wraps console.log and the wrapper function performs the action I need? is there anything better than this? This isn't all that feasible, and it'd be much easier to just listen for an onConsole event

function logWrapper(msg,fn){
   console.log(msg)
   fn();
}
answer1: 回答1:

I don't see any events at all in the API documentation for console, which surprised me to be truthful.

If this is for your own code, a wrapper function is the way to go.

If you need to also listen in on messages from other code, you could try replacing log:

var realLog = console.log;
console.log = function() {
    // ...your code...

    // Pass off to the real one
    return realLog.apply(console, arguments);
};

...but I'd avoid that if you reasonably can.

我在控制台的API文档中没有看到任何事件,这让我感到惊讶。

如果这是为您自己的代码,包装功能是走的路。

如果您还需要收听其他代码的消息,可以尝试替换日志:

var realLog = console.log;
console.log = function() {
    // ...your code...

    // Pass off to the real one
    return realLog.apply(console, arguments);
};

但是如果你合理的话我会避免的。

javascript  node.js