diff --git a/README.md b/README.md index b998135..8bfdf2e 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,12 @@ be the same by default, but specifying `duplicates: true` would yield: } ``` +`noCache`: Prevent file caching. Could be useful using gulp.watch or other watch requiring refreshed file content Default is false. + +```js +requireDir('./dir', { noCache: true }) +``` + ## Tips Make an `index.js` in a directory with this code to clean things up: diff --git a/index.js b/index.js index 0c5ac7f..31ea45a 100644 --- a/index.js +++ b/index.js @@ -113,6 +113,11 @@ module.exports = function requireDir(dir, opts) { continue; } + // delete cache + if (opts.noCache) { + delete require.cache[abs]; + } + // if duplicates are wanted, key off the full name always, and // also the base if it hasn't been taken yet (since this ext // has higher priority than any that follow it). if duplicates diff --git a/test/noCache.js b/test/noCache.js new file mode 100644 index 0000000..7560d53 --- /dev/null +++ b/test/noCache.js @@ -0,0 +1,59 @@ +var assert = require("assert"); +var requireDir = require(".."); +var fs = require("fs"); + +var cachedResult = { + a: "a", + b: "b" +}; + +var notCachedResult = { + a: "c", + b: "b" +}; + +// filter the results to a particular file: +assert.deepEqual(requireDir("./noCache", { noCache: false }), cachedResult); + +var promiseFileModification = new Promise(function(resolve, reject) { + fs.writeFile("test/noCache/a.js", "module.exports = 'c';", "ascii", function( + error + ) { + if (error) { + reject(error); + } else { + resolve(); + } + }); +}); + +promiseFileModification.then( + function() { + // Check if cache is active that it is the same result + assert.deepEqual(requireDir("./noCache", { noCache: false }), cachedResult); + + // Check by removing cache that the result is the new content + assert.deepEqual( + requireDir("./noCache", { noCache: true }), + notCachedResult + ); + + console.log("noCache tests passed."); + + fs.writeFile( + "test/noCache/a.js", + "module.exports = 'a';", + "ascii", + function(error) { + if (error) { + console.error("noCache tests, issue to reset test."); + console.error(error); + } + } + ); + }, + function(error) { + console.error("noCache tests failed."); + console.error(error); + } +); diff --git a/test/noCache/a.js b/test/noCache/a.js new file mode 100644 index 0000000..7a7cf93 --- /dev/null +++ b/test/noCache/a.js @@ -0,0 +1 @@ +module.exports = 'a'; \ No newline at end of file diff --git a/test/noCache/b.json b/test/noCache/b.json new file mode 100644 index 0000000..19010cc --- /dev/null +++ b/test/noCache/b.json @@ -0,0 +1 @@ +"b"