javascript - 如何从 Javascript 将字符串写入标准输出

标签 javascript node.js rhino java-8 nashorn

我对一种将字符串写入标准输出的可移植方式很感兴趣,没有在末尾添加隐式换行符,理想情况下强制编码为 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/

相关文章:

javascript - 尝试使用 JS (Angular) 跨站点 JSON 请求 API

javascript - 如何在 Angular 2/4+ 和 Socket.io 中关闭 websocket

javascript - 在 Rhino 上运行 CoffeeKup?

java - 从 javascript/rhino 调用带有 int 参数的 java 方法

javascript - nodejs : Async.系列只执行第一个函数就停止了

java - 如何使用 Rhino 和 Eclipse 从 JavaScript 访问外部 JAR 文件?

javascript - 有没有更好的方法来获取 outerHtml?

javascript - IntelliJ IDEA 中的 P5.js?

javascript - 创建一个接受对象文字的函数并从该对象的成员创建一个类

mysql - NodeJS : Nested SQL query for custom REST API endpoint