Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhantomJS require() a relative path

In a PhantomJS script I would like to load a custom module but it seems relative paths do not works in PhantomJS ?

script.js:

var foo = require('./script/lib/foo.js');
foo.bar('hello world');
phantom.exit();

foo.js:

exports.bar = function(text){
  console.log(text);
}
  • According to fs.workingDirectory I am in the good directory
  • foo.js is not in the lookup path of phantomjs

Am I missing something ?

EDIT:

inject() is not revelant because I do not need to inject a JS to an HTML page but instead load my own module like require('fs') but with a relative path.

like image 323
Jean-Philippe Encausse Avatar asked Aug 08 '12 22:08

Jean-Philippe Encausse


1 Answers

After a lot of time searching for the same thing, here is what I understood, though I might be wrong :

  • PhantomJS doesn't use Node's require, but its own require, so things are different
  • when providing a relative path to phantomjs's require, it is always interpreted as relative to the current working directory
  • PhantomJS doesn't implement node's __dirname, and as such there is no direct way to have the directory of your script

The solution I found least annoying :

  • if using phantomjs pure, without casperjs :

    require(phantom.libraryPath + '/script/lib/foo.js')
    
  • if using casperjs :

    var scriptName = fs.absolute( require("system").args[3] );
    var scriptDirectory = scriptName.substring(0, scriptName.lastIndexOf('/'));
    require(scriptDirectory + '/script/lib/foo.js')
    
like image 187
Vic Seedoubleyew Avatar answered Oct 27 '22 23:10

Vic Seedoubleyew