Is it possible to get a list of all the javascript files in the libraries directory? So far I have tried using files_scan directory but it's not returning anything:

$dir = base_path() . 'sites/all/libraries/';
$files = file_scan_directory($dir, "/.*\.js$/");

many thanks.


I changed to using DRUPAL_ROOT. This gives the correct path and returns an array of js files but there is a double slash // in the uri just before the file names: /var/www/html/droop/sites/all/libraries//d3/d3.min.js

$dir = DRUPAL_ROOT . '/sites/all/libraries/';
$files = file_scan_directory($dir, "/.*\.js$/");
  • out of interest, why do you need to do this? – autopoietic Dec 15 '14 at 16:28
  • a module with a field that to allows admin to pick from a set of js files to load with an HTML5 canvas element on each blog post. – RobotEyes Dec 15 '14 at 16:38
  • that is because you have a slash after the path you are searching for ('/sites/all/libraries**/**'). just remove the trailing slash there – autopoietic Dec 15 '14 at 17:06

libraries_get_libraries should return an array of library directories, with the library name as the key and the directory as the value.

libraries_get_path will get you the path to a specific library (js).

Follwing your approach, this works fine for me:

  $dir = "sites/all/libraries";
  $files = file_scan_directory($dir, '/.*\.js$/');

I think it might be base_path that is breaking it in your example, as it adds a / in front of the (relative) path from the site root.

Combining libraries_get_libraries with file_scan_directory will also get you libraries from profile and site specific directories:

$libraries_array = libraries_get_libraries();
foreach($libraries_array as $library => $directory) {
  $files = file_scan_directory($directory, '/.*\.js$/');
  $js_paths[$library] = $files;

It may be worth noting that these libraries may contain many javascript files that are not actually used by modules.

| improve this answer | |

I am looking into it a little more but for starters does dpm() show the correct value for $dir? Also, according to the documentation the trailing slash on $dir is not supposed to be there.

code that is working for me:

$dir = DRUPAL_ROOT . '/sites/all/libraries';
$files = file_scan_directory($dir, '/.*\.js/');
| improve this answer | |
  • Using DRUPAL_ROOT instead of base_path() fixes the path but there is a double slash in the file uri now (see my edit) thanks – RobotEyes Dec 15 '14 at 16:58
  • Is there a trailing slash on $dir? – sareed Dec 15 '14 at 17:06
  • ah yes. It works with DRUPAL_ROOT if I take off the trailing slash and add a leading slash. $dir = DRUPAL_ROOT . '/sites/all/libraries'; – RobotEyes Dec 15 '14 at 17:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.