PhantomJS fails to open local file

2019-01-13 05:59发布

问题:

I am trying to open a local HTML-file with PhantomJS (version 1.9.2):

var page = require('webpage').create(), fs = require('fs'),
    address = "/Full/Path/To/test.html";

console.log('isFile? ' + fs.isFile(address));
console.log('isReadable? ' + fs.isReadable(address));
page.open(address, function(status){
    console.log('status? ' + status);
    console.log(page.content)
    phantom.exit();
});

First I check if I got the right path and if the file is readable using fs.isFile() & fs.isReadable(). Then I check whether phantomjs succeeded in opening the file (with status). Independent of the actual contents of the file I always get:

isFile? true
isReadable? true
status? fail
<html><head></head><body></body></html>

So the file and the path seem to be okay – but PhantomJS fails to open it! Any suggestions?

回答1:

PhantomJS can open local files without any problems. The url have to follow classic Url/Uri rules, especially for a local file.

/Full/Path/To/test.html is not valid for PhantomJS. Is it a local file or a web ressource ?

Depending of the path, just try with somethting like this :

file:///C://Full/Path/To/test.html

or if it's hosted in a web server

http://localhost/Full/Path/To/test.html


回答2:

An addition to @Cybermaxs answer: If you need to convert a simple relative path test.html to a proper URL, you can do so by something like this:

var fs = require('fs');

function getFileUrl(str) {
  var pathName = fs.absolute(str).replace(/\\/g, '/');
  // Windows drive letter must be prefixed with a slash
  if (pathName[0] !== "/") {
    pathName = "/" + pathName;
  }
  return encodeURI("file://" + pathName);
};

var fileUrl = getFileUrl("test.html");

Note that you can't use a solution based on file-url because it is based on path and process, which do not work within PhantomJS. Fortunately, the fs module provides similar functionality.



回答3:

As of phantom 2.1.1 (possibly earlier) the method described by OP actually works as written.



标签: phantomjs