fs.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * Module dependencies.
  3. */
  4. var crypto = require('crypto')
  5. , fs = require('fs')
  6. , join = require('path').join
  7. , version = require('../../package').version
  8. , nodes = require('../nodes');
  9. var FSCache = module.exports = function(options) {
  10. options = options || {};
  11. this._location = options['cache location'] || '.styl-cache';
  12. if (!fs.existsSync(this._location)) fs.mkdirSync(this._location);
  13. };
  14. /**
  15. * Set cache item with given `key` to `value`.
  16. *
  17. * @param {String} key
  18. * @param {Object} value
  19. * @api private
  20. */
  21. FSCache.prototype.set = function(key, value) {
  22. fs.writeFileSync(join(this._location, key), JSON.stringify(value));
  23. };
  24. /**
  25. * Get cache item with given `key`.
  26. *
  27. * @param {String} key
  28. * @return {Object}
  29. * @api private
  30. */
  31. FSCache.prototype.get = function(key) {
  32. var data = fs.readFileSync(join(this._location, key), 'utf-8');
  33. return JSON.parse(data, FSCache.fromJSON);
  34. };
  35. /**
  36. * Check if cache has given `key`.
  37. *
  38. * @param {String} key
  39. * @return {Boolean}
  40. * @api private
  41. */
  42. FSCache.prototype.has = function(key) {
  43. return fs.existsSync(join(this._location, key));
  44. };
  45. /**
  46. * Generate key for the source `str` with `options`.
  47. *
  48. * @param {String} str
  49. * @param {Object} options
  50. * @return {String}
  51. * @api private
  52. */
  53. FSCache.prototype.key = function(str, options) {
  54. var hash = crypto.createHash('sha1');
  55. hash.update(str + version + options.prefix);
  56. return hash.digest('hex');
  57. };
  58. /**
  59. * JSON to Stylus nodes converter.
  60. *
  61. * @api private
  62. */
  63. FSCache.fromJSON = function(key, val) {
  64. if (val && val.__type) {
  65. val.__proto__ = nodes[val.__type].prototype;
  66. }
  67. return val;
  68. };