简体   繁体   中英

Implementing stdout.write / stderr.write in browser

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?

This should work:

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));
};

Ditto for stderr.

But you'll need a way to flush the last slice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM