filesystem.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. var fs = require('fs')
  2. var path = require('path')
  3. /**
  4. * Loads templates from the file system.
  5. * @alias swig.loaders.fs
  6. * @example
  7. * swig.setDefaults({ loader: swig.loaders.fs() });
  8. * @example
  9. * // Load Templates from a specific directory (does not require using relative paths in your templates)
  10. * swig.setDefaults({ loader: swig.loaders.fs(__dirname + '/templates' )});
  11. * @param {string} [basepath=''] Path to the templates as string. Assigning this value allows you to use semi-absolute paths to templates instead of relative paths.
  12. * @param {string} [encoding='utf8'] Template encoding
  13. */
  14. module.exports = function (basepath, encoding) {
  15. var ret = {}
  16. encoding = encoding || 'utf8'
  17. basepath = basepath ? path.resolve(basepath) : null
  18. /**
  19. * Resolves <var>to</var> to an absolute path or unique identifier. This is used for building correct, normalized, and absolute paths to a given template.
  20. * @alias resolve
  21. * @param {string} to Non-absolute identifier or pathname to a file.
  22. * @param {string} [from] If given, should attempt to find the <var>to</var> path in relation to this given, known path.
  23. * @return {string}
  24. */
  25. ret.resolve = function (to, from) {
  26. if (basepath) {
  27. from = basepath
  28. } else {
  29. from = from ? path.dirname(from) : process.cwd()
  30. }
  31. return path.resolve(from, to)
  32. }
  33. /**
  34. * Loads a single template. Given a unique <var>identifier</var> found by the <var>resolve</var> method this should return the given template.
  35. * @alias load
  36. * @param {string} identifier Unique identifier of a template (possibly an absolute path).
  37. * @param {function} [cb] Asynchronous callback function. If not provided, this method should run synchronously.
  38. * @return {string} Template source string.
  39. */
  40. ret.load = function (identifier, cb) {
  41. if (!fs || (cb && !fs.readFile) || !fs.readFileSync) {
  42. throw new Error(
  43. 'Unable to find file ' +
  44. identifier +
  45. ' because there is no filesystem to read from.'
  46. )
  47. }
  48. identifier = ret.resolve(identifier)
  49. if (cb) {
  50. fs.readFile(identifier, encoding, cb)
  51. return
  52. }
  53. return fs.readFileSync(identifier, encoding)
  54. }
  55. return ret
  56. }