我对一种将字符串写入标准输出的可移植方式很感兴趣,没有在末尾添加隐式换行符,理想情况下强制编码为 UTF-8,它适用于
- jrunscript(来自任何 JDK)
- 犀牛
- node.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,我一直在使用函数 print
,但这代表 JDK-8021773 改变了它在 JDK-8 中的行为。 .
最佳答案
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...
没有,因为 javascript 没有“系统 api”。 JS 核心是有限的,您需要使用运行 javascript 引擎的环境中可用的 api。
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.
这是你唯一能做的。
编辑:javascript 规范在这里:http://es5.github.io/简而言之,标准输出或标准输入的概念为 0,因为没有 javascript 标准库。
关于javascript - 如何从 Javascript 将字符串写入标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22506399/