nodejs调用phantomjs时,phantomjs.path为null,应该要怎么处理?
发布于 7 年前 作者 smilesrain 4571 次浏览 来自 问答

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 回复

官方案例 : 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 打出来看看是什么错误

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

@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)

@zaaack 我也想过这个问题…但貌似不行

@smilesrain 因为源代码里面

var location = require('./location')  

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

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

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

回到顶部