Implementing stdout.write / stderr.write in browser

时间:2017-04-10 02:38:51

标签: javascript node.js browser stdout stderr

I have some Node.js code, and would like to get it running the browser. In many places in my Node.js code, I have made calls to process.stdout.write and process.stderr.write.

In the browser, we have console.log / console.error

I do not need high-performance here. If I implement these methods in the browser like so:

process.stdout.write = function(v){
   console.log(v);
};

process.stdout.error = function(v){
   console.error(v);
};

that's obviously not going to really get us what we want. Is there a way to hook into console.log / console.error in the browser to print to stdout/stderr without printing a newline char?

1 个答案:

答案 0 :(得分:0)

这应该有效:

var stdout = '';
process.stdout.write = function(s) {
  stdout += s;
  for (var i; -1 !== (i = stdout.indexOf('\n')); stdout = stdout.slice(i + 1))
    console.log(stdout.slice(0, i));
};

同上stderr。

但是你需要一种方法来冲洗最后一片。