2

我对将字符串写入标准输出的可移植方式感兴趣,无需在末尾添加隐式换行符,理想情况下强制编码为 UTF-8,适用于

  • jrunscript(来自任何 JDK)
  • 犀牛
  • 节点.js

我当前的代码尝试检测它在哪里运行,然后使用特定于平台的写入方法:

  if (typeof process !== "undefined") {     // assume node.js
    var log = function(string) {process.stdout.write(string);};
  }
  else if (typeof println == "undefined") { // assume rhino
    var log = function(string) {java.lang.System.out.write(java.lang.String(string).getBytes("utf-8"));};
  }
  else {                                    // assume jrunscript
    var log = function(string) {java.lang.System.out.print(string);};
  }
  log("X");
  log("Y");

它应该导致:

  XY

这可以做得更好吗?

对于 jrunscript,我一直在使用 function print,但这代表JDK-8021773改变了它在 JDK-8 中的行为。

4

1 回答 1

3

I am interested in a portable way of writing a string to standard output, without implicit newlines added to the end, ideally forcing encoding to UTF-8, that works with either of...

there is none,since javascript doesnt have "system apis". JS core is limited and you need to use the api available within the environment javascript engine is running in.

My current code tries to detect where it is running, then uses a platform-specific write method. But I'd rather get rid of that.

that's the only thing you can do.

EDIT : the javascript spec is here : http://es5.github.io/ and it's short,there is 0 notion of standard output or standard input because there is no javascript standard library.

于 2014-03-19T17:05:52.130 回答