Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>module.paths</code> stores array of search paths for <code>require</code>. Search paths are relative to the current module from where <code>require</code> is called. So:</p> <pre><code>var fs = require("fs"); // checks if module is available to load var isModuleAvailableSync = function(moduleName) { var ret = false; // return value, boolean var dirSeparator = require("path").sep // scan each module.paths. If there exists // node_modules/moduleName then // return true. Otherwise return false. module.paths.forEach(function(nodeModulesPath) { if(fs.existsSync(nodeModulesPath + dirSeparator + moduleName) === true) { ret = true; return false; // break forEach } }); return ret; } </code></pre> <p>And asynchronous version:</p> <pre><code>// asynchronous version, calls callback(true) on success // or callback(false) on failure. var isModuleAvailable = function(moduleName, callback) { var counter = 0; var dirSeparator = require("path").sep module.paths.forEach(function(nodeModulesPath) { var path = nodeModulesPath + dirSeparator + moduleName; fs.exists(path, function(exists) { if(exists) { callback(true); } else { counter++; if(counter === module.paths.length) { callback(false); } } }); }); }; </code></pre> <p>Usage:</p> <pre><code>if( isModuleAvailableSync("mocha") === true ) { console.log("yay!"); } </code></pre> <p>Or:</p> <pre><code>isModuleAvailable("colors", function(exists) { if(exists) { console.log("yay!"); } else { console.log("nay:("); } }); </code></pre> <p>Edit: Note:</p> <ul> <li><code>module.paths</code> is not in the <a href="http://nodejs.org/api/modules.html" rel="nofollow">API</a></li> <li>Documentation <a href="http://nodejs.org/api/modules.html#modules_loading_from_the_global_folders" rel="nofollow">states</a> that you can add paths that will be scanned by <code>require</code> but I couldn't make it work (I'm on Windows XP).</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload