reading/reader.js

  1. 'use strict'
  2. const Node = require('node-html-light').Node
  3. const fs = require('fs')
  4. const globby = require('globby')
  5. const resolve = require('path').resolve
  6. /** */
  7. class FileReader {
  8. constructor(basePath) {
  9. this._basePath = basePath
  10. this._fileCache = {}
  11. }
  12. /**
  13. * @param {Array<String>} arguments an array of path elements that will,
  14. * once joined and resolved relative to the root directory, point to a html file that will be read and parsed
  15. * @returns {Node|Array<Node>} a single node or an array of nodes depending on the input file
  16. */
  17. readNode() {
  18. const path = resolve.apply(null, arguments)
  19. return Node.fromPath(path)
  20. }
  21. /**
  22. * @param {Array<String>} arguments an array of path elements that will,
  23. * once joined and resolved relative to the root directory, point to a html file that will be read and parsed
  24. * @returns {Array<Node>} an array of HTML Nodes
  25. */
  26. readNodes(root, path) {
  27. if (!path) {
  28. path = root
  29. root = this._basePath
  30. }
  31. const resolvedPath = resolve(root, path)
  32. this._readFileFromDisk(resolvedPath).then((text) => {
  33. const node = Node.fromString(text)
  34. return this._isArrayElseToArray(node)
  35. })
  36. }
  37. _isArrayElseToArray(node) {
  38. if (Array.isArray(node)) {
  39. return node
  40. } else {
  41. return [node]
  42. }
  43. }
  44. _readFileFromDisk(fullPath) {
  45. return new Promise((resolve, reject) => {
  46. fs.readFile(fullPath, 'utf-8', (err, data) => {
  47. if (err) {
  48. reject(err)
  49. } else {
  50. resolve(data)
  51. }
  52. })
  53. })
  54. }
  55. /**
  56. * @param {String|Array<String>} pattern a single glob pattern or an array of patterns
  57. * @param {String} root the root directory to start looking for files matching the pattern
  58. * @returns {Promise<Array.String>} a promise that will be resolved with an array of files matching the pattern starting from the root directory
  59. */
  60. matchFiles(pattern, root) {
  61. if (!Array.isArray(pattern)) {
  62. pattern = [pattern]
  63. }
  64. return globby(pattern, {
  65. cwd: root,
  66. nodir: true
  67. })
  68. }
  69. }
  70. module.exports = FileReader