CNode

nodejs调用phantomjs时,phantomjs.path为null,应该要怎么处理?

问答
Ssmilesrain发布于10 年前最后回复10 年前7 回复5441 浏览0 收藏

var path = require('path'); var childProcess = require('child_process'); var Q = require('q'); var phantomjs = require('phantomjs'); var binPath = phantomjs.path; .... childProcess.execFile(binPath, childArgs, function (err, stdout, stderr) { console.log(stdout); console.log(stderr);

// handle results
deferred.resolve();

}); 这段代码中binPath,也就是phantomjs.path是空的,线上服务器的phantomjs通过npm安装了,但是就是为null,完全不知道怎么办。因为我是搞java的,公司这个是之前遗留的系统,现在一脸懵逼求各位大神帮忙下,感激不尽!!!

查看回复

回复 (7)

S
SunilWang#1·10 年前

官方案例 : Running via node

The package exports a path string that contains the path to the phantomjs binary/executable.

Below is an example of using this package via node.

var path = require('path')
var childProcess = require('child_process')
var phantomjs = require('phantomjs-prebuilt')
var binPath = phantomjs.path

var childArgs = [
  path.join(__dirname, 'phantomjs-script.js'),
  'some other argument (passed to phantomjs script)'
]

childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) {
  // handle results
})

或者。。。

to see : https://github.com/Medium/phantomjs 去看源码18行 => https://github.com/Medium/phantomjs/blob/master/lib/phantomjs.js#L18

/**
 * Where the phantom binary can be found.
 * @type {string}
 */
try {
  var location = require('./location')
  exports.path = path.resolve(__dirname, location.location)
  exports.platform = location.platform
  exports.arch = location.arch
} catch(e) {
  // Must be running inside install script.
  exports.path = null
}

你可以把 catch 的 e 打出来看看是什么错误

Z
zaaack#2·10 年前

正确的解决方案是使用 phantomjs-node 不过如果代码重构成本太高的话,目测可能和 phantomjs 包太新有关,可以找个老版本试下

S
smilesrain#3·10 年前
引用 SunilWang官方案例 : Running via node The package exports a path string that contains the path to the phantomj...

@KingTree 打印出来是这样的

{ Error: Cannot find module './location' at Function.Module._resolveFilename (module.js:469:15) at Function.Module._load (module.js:417:25) at Module.require (module.js:497:17) at require (internal/module.js:20:19)

S
SunilWang#5·10 年前
引用 smilesrain@KingTree 打印出来是这样的 { Error: Cannot find module './location' at Function.Module. resolveFilename ...

@smilesrain 因为源代码里面

var location = require('./location')  

有这行。github项目里面也没有location这个文件模块

S
smilesrain#6·10 年前
引用 zaaack正确的解决方案是使用 phantomjs node 不过如果代码重构成本太高的话,目测可能和 phantomjs 包太新有关,可以找个老版本试下

@zaaack 我刚才访问了一下package.json,发现里面使用的版本是1.9.17,然后用cnpm install了一下,结果可以了!!!非常感谢!!!

S
smilesrain#7·10 年前
引用 SunilWang@smilesrain 因为源代码里面 有这行。github项目里面也没有location这个文件模块

@KingTree 恩,确实是缺少这个模块,但是是由于phantomjs的版本问题造成的。非常感谢帮我解决这个问题

参与回复
登录后即可参与回复。登录