Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

first passing test hooray

  • Loading branch information...
commit 169e4860a1dcf27c66ea49d885c7ed0656886de2 0 parents
@substack authored
Showing with 88 additions and 0 deletions.
  1. +6 −0 README.markdown
  2. +45 −0 index.js
  3. +37 −0 test/cache.js
6 README.markdown
@@ -0,0 +1,6 @@
+deputy
+======
+
+This module is a drop-in replacement around
+[node-detective](http://github.com/substack/node-detective)
+with a global caching layer.
45 index.js
@@ -0,0 +1,45 @@
+var fs = require('fs');
+var path = require('path');
+var crypto = require('crypto');
+
+var mkdirp = require('mkdirp');
+var detective = require('detective');
+
+module.exports = function (cacheFile) {
+ mkdirp.sync(path.dirname(cacheFile), 0700);
+
+ var cache = {};
+ if (path.existsSync(cacheFile)) {
+ var body = fs.readFileSync(cacheFile);
+ try {
+ cache = JSON.parse(body);
+ }
+ catch (err) {}
+ }
+
+ function save (h, res) {
+ cache[h] = res;
+ fs.writeFile(cacheFile, JSON.stringify(cache));
+ }
+
+ function hash (src) {
+ return new crypto.Hash('md5').update(src).digest('hex');
+ }
+
+ var deputy = function (src) {
+ return deputy.find(src).strings;
+ };
+
+ deputy.find = function (src) {
+ var h = hash(src);
+ var c = cache[h];
+ if (c) return c;
+ else {
+ c = detective.find(src);
+ save(h, c);
+ return c;
+ }
+ };
+
+ return deputy;
+};
37 test/cache.js
@@ -0,0 +1,37 @@
+var test = require('tap').test;
+var deputy = require('../');
+var fs = require('fs');
+var crypto = require('crypto');
+
+test('cache with new file', function (t) {
+ var ps = []; for (var i = 0; i < 10; i++) {
+ ps.push(Math.floor(Math.random() * (1<<30)).toString(16));
+ }
+ var file = '/tmp/' + ps.join('/') + '.json';
+ var detective = deputy(file);
+
+ var src = [
+ [
+ 'require("a"); require("b")',
+ { strings : ['a','b'], expressions : [] }
+ ]
+ ];
+ t.deepEqual(detective.find(src[0][0]), src[0][1]);
+
+ setTimeout(function () {
+ fs.readFile(file, function (err, body) {
+ t.deepEqual(
+ src.reduce(function (acc,s) {
+ acc[hash(s[0])] = s[1];
+ return acc;
+ }, {}),
+ JSON.parse(body)
+ );
+ t.end();
+ });
+ }, 100);
+
+ function hash (src) {
+ return new crypto.Hash('md5').update(src).digest('hex');
+ }
+});
Please sign in to comment.
Something went wrong with that request. Please try again.