34

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?

AvL
  • 3,083
  • 1
  • 28
  • 39
  • Why don't you use the page.onLoadFinished callback like I have in this answer? http://stackoverflow.com/a/7549515/541404 – Cameron Tinker Nov 13 '13 at 13:25
  • 2
    Also, what operating system are you using? You may want to use `fs.separator` to get the appropriate file system separator. For example, if you're in Windows, your separator will be "\", but if you're in a Unix\OS X variant, you'll use "/". – Cameron Tinker Nov 13 '13 at 13:41
  • I was missing the third "/" on "file:///". It made phantom give me success as status but as content. Weird. – Marcos Brigante Jul 28 '15 at 21:11

3 Answers3

53

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 resource?

Depending of the path, just try with something 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,561
  • 4
  • 25
  • 71
Cybermaxs
  • 24,378
  • 8
  • 83
  • 112
  • 10
    @MiguelAlejandroFuentesLopez: Unix path is not a full Uniform Resource Identifier as described in [RFC 3986](http://tools.ietf.org/html/rfc3986). – adrenalin Aug 28 '14 at 08:54
4

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.

Community
  • 1
  • 1
bluenote10
  • 23,414
  • 14
  • 122
  • 178
0

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

chiliNUT
  • 18,989
  • 14
  • 66
  • 106