【问题标题】:Get unix hostname from PhantomJS从 PhantomJS 获取 unix 主机名
【发布时间】:2016-03-30 17:00:13
【问题描述】:

我使用 PhantomJS 开发一个将在 Unix 服务器上执行的脚本。 从 PhantomJS 中,我想获取 hostname 命令返回的 Unix 系统的名称。

我这样做

var childProcess = require('child_process')

childProcess.execFile("hostname", [""], null, function (err, stdout, stderr) {
  console.log("execFileSTDOUT:", JSON.stringify(stdout))
  console.log("execFileSTDERR:", JSON.stringify(stderr))
  console.log("execFileERR:", JSON.stringify(err))
})

但没有任何显示。

【问题讨论】:

  • 这是你的完整剧本吗?我怀疑你退出得太早了。

标签: javascript unix command phantomjs


【解决方案1】:

请记住,execFile 是异步的。如果您要退出 PhantomJS 脚本,则需要在回调中执行此操作。此外,"" 不是有效的主机名。您可以使用空参数列表:

var childProcess = require('child_process')

childProcess.execFile("hostname", [], null, function (err, stdout, stderr) {
  console.log("execFileSTDOUT:", JSON.stringify(stdout))
  console.log("execFileSTDERR:", JSON.stringify(stderr))
  console.log("execFileERR:", JSON.stringify(err))
  phantom.exit();
})

输出:

execFileSTDOUT: "myhostname\n"
execFileSTDERR: ""
execFileERR: null

使用 PhantomJS 1.9.7 和 2.0.1 测试。

【讨论】:

  • 可以使用 PhantomJS 2.0.0。你认为,是否可以同步执行execFile
【解决方案2】:

丢失第二个和第三个参数(你没有发送任何东西,所以没关系)

var childProcess = require('child_process')

childProcess.execFile("hostname", [], {}, function (err, stdout, stderr) {
  console.log("execFileSTDOUT:", JSON.stringify(stdout))
  console.log("execFileSTDERR:", JSON.stringify(stderr))
  console.log("execFileERR:", JSON.stringify(err))
})

// execFileSTDOUT: "YourPuterName\n"

【讨论】:

  • 我收到此错误:错误:调用 _start() 时参数类型不兼容;候选人是 _start(QString,QStringList) :95 in _start :95 in execFile
  • 你运行的是哪个版本的 Node?​​span>
  • Ubuntu 15.04 上的 PhantomJS V 2.0.0 - ARMv7 处理器版本 2 (v7l)
  • @Wainage PhantomJS 完全独立于节点。它只有两个同名模块,但功能和实现不同。
  • @LeMoussel。我已经更新了我的代码并在 PhantomJS 2.1.1 上对其进行了测试。效果很好。您必须传入一个空数组,否则空字符串似乎被发送到hostname "",这不会产生结果。
猜你喜欢
  • 1970-01-01
  • 2015-07-08
  • 1970-01-01
  • 2016-12-17
  • 2013-11-20
  • 2010-12-26
  • 2012-05-31
  • 2012-03-26
  • 1970-01-01
相关资源
最近更新 更多