1

我使用 v8-shell 进行研究。我需要从我的 JS 脚本中读取“stdin”。

例如,我将 JS 脚本运行为: cat textfile.txt | ./v8-shell myscript.js

在我的“myscript.js”中,我需要读取传递给标准输入的数据。

是否可以?我怎样才能做到这一点?

谢谢。

4

3 回答 3

3

v8 不提供 I/O 库。它基本上只是核心 JavaScript 语言的运行时,提供了一些对象,如 Math、String 和 Array 作为一部分。

缺少I/O 等重要模块是因为它们在浏览器环境中没有用处,而 v8 是作为此类环境的一个组件来实现的。为了能够将 v8 用作独立的编程环境,至少需要具有用于基本 I/O 的本机库。在这里,您有两个选择:实现 v8 的 I/O 扩展或使用现有的扩展。前者需要 C++ 知识,因为 v8 是用 C++ 实现的,并提供用于 C++ 扩展的 api。后一种选择更容易。您可以在此类库的许多实现之间进行选择。

一个流行的库是node.js,它为 I/O 和网络提供了一个详尽的事件驱动的、主要是异步的 api。如果您可以使用node.js ,则通过process模块在其中提供对 stdin、stdout 和 stderr 的访问。快速链接:process.stdin

另一个项目是CommonJs,它是一个列表规范和它的大量实现,致力于提供 API(带或不带 I/O)以供在浏览器环境之外使用 JS。许多实现都在 v8 之上,在http://commonjs.org/impl/中列出。

另一个这样的项目是 Gnome 的Seed,它提供了一个 API,包括 GObjectInstrospection。它还使用自定义 JS 运行时,因此如果您需要坚持使用 v8,这不是您的选择。Seed 还值得注意的是它是用 C 语言实现和扩展的。

于 2013-02-13T17:39:17.517 回答
1

答案是肯定的。您可以使用该readline()功能。

我在 ECMAScript 规范中没有看到它,但是 Google v8、WebKit 的 JavaScriptCore 和 Mozilla SpiderMonkey都支持它(并且已经支持了很长一段时间)。

于 2014-09-23T14:44:42.587 回答
0

请看一下符合 common.js 并且基于 v8 的teajs - 这是我知道的唯一一个让您构建 apache 'mod_teajs' 模块的项目(我认为 node.js 服务器尚未准备好生产)它确实有标准的 IO。

stdin
system.stdin.read(count) - read count bytes from standard input. The data is returned as an instance of Buffer. If count == 0, all available data is read. 
system.stdin.readLine([count]) - reads a line from standard input. If count is not specified, reads up to 65535 bytes. When no data is available, returns null. 

stdout
system.stdout.write(data) - write data to standard output. Data can be either string or Buffer. 
system.stdout.writeLine(data) - write data followed by a line break to standard output. Data can be either string or Buffer. 
system.stdout.flush() - flushes stdout 

stderr
system.stderr.write(data) - write data to standard error output. Data can be either string or Buffer. 
system.stderr.writeLine(data) - write data followed by a line break to standard error output. Data can be either string or Buffer. 
system.stderr.flush() - flushes stderr
于 2013-12-15T20:42:42.780 回答