如何在CasperJS/PantomJS脚本中与用户交互



想象一下这样的脚本

system = require "system"
system.stdout.write "What's your name? "
name = system.stdin.readLine()
system.stdout.writeLine "Hello, #{name}" 

通过运行

casperjs name.coffee

我希望能够在用于运行脚本的终端中与用户交互,但我被readLine()调用卡住了。

正如GarethOwen所指出的,这确实是可能的。以下是Unix命令cat:的一个非常基本的CasperJS实现
var system = require('system'),
    casper = require('casper').create();
while (!system.stdin.atEnd()) {
    var line = system.stdin.readLine();
    casper.log(line);
}
casper.exit();

请注意,此模块主要是在C++中实现的:https://github.com/ariya/phantomjs/blob/master/src/system.h

并且stdin/stdout/stderr是PhantomJs类File的实例:https://github.com/ariya/phantomjs/blob/master/src/filesystem.h

根据文档,phantomJS可以与标准输入进行通信。参见此示例:

https://github.com/ariya/phantomjs/blob/master/examples/stdin-stdout-stderr.js

关于过程间通信的文件如下:

https://github.com/ariya/phantomjs/wiki/Inter-Process-Communication

但我自己从来没有试过。

最新更新