Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhantomJS fails to open local file

Tags:

phantomjs

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?

like image 589
AvL Avatar asked Nov 12 '13 20:11

AvL


2 Answers

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 
like image 178
Cybermaxs Avatar answered Sep 19 '22 12:09

Cybermaxs


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.

like image 20
bluenote10 Avatar answered Sep 18 '22 12:09

bluenote10