PhantomJS require() a relative path

后端 未结 5 526
情书的邮戳
情书的邮戳 2021-02-04 03:07

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(\'./scrip         


        
5条回答
  •  攒了一身酷
    2021-02-04 03:57

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

提交回复
热议问题