V8 shell和stdin读取

时间:2013-02-13 17:30:23

标签: javascript v8

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

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

在我的'myscript.js'中,我需要读取传递给stdin的数据。

有可能吗?我怎么能这样做?

感谢。

3 个答案:

答案 0 :(得分:3)

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

缺少重要的模块(如I / O)是因为它们在浏览器环境中没有用,而v8是作为此类环境的一个组件实现的。为了能够将v8用作独立的编程环境,需要至少具有基本I / O的本机库。这里有两个选择:实现v8的I / O扩展或使用现有的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,那么这不是您的选择。还有一点值得关注的是它是用C语言实现和扩展的。

答案 1 :(得分:1)

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

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

答案 2 :(得分: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