ext.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. const fs = require('fs-extra')
  2. const os = require('os')
  3. const path = require('path')
  4. const util = require('util')
  5. const exec = util.promisify(require('child_process').exec)
  6. const { pipeline } = require('stream/promises')
  7. module.exports = {
  8. key: 'sharp',
  9. title: 'Sharp',
  10. description: 'Process and transform images. Required to generate thumbnails of uploaded images and perform transformations.',
  11. async isCompatible () {
  12. return os.arch() === 'x64'
  13. },
  14. isInstalled: false,
  15. isInstallable: true,
  16. async check () {
  17. this.isInstalled = await fs.pathExists(path.join(process.cwd(), 'node_modules/sharp/wiki_installed.txt'))
  18. return this.isInstalled
  19. },
  20. async install () {
  21. try {
  22. const { stdout, stderr } = await exec('node install/libvips && node install/dll-copy', {
  23. cwd: path.join(process.cwd(), 'node_modules/sharp'),
  24. timeout: 120000,
  25. windowsHide: true
  26. })
  27. await fs.ensureFile(path.join(process.cwd(), 'node_modules/sharp/wiki_installed.txt'))
  28. this.isInstalled = true
  29. WIKI.logger.info(stdout)
  30. WIKI.logger.warn(stderr)
  31. } catch (err) {
  32. WIKI.logger.error(err)
  33. }
  34. },
  35. sharp: null,
  36. async load () {
  37. if (!this.sharp) {
  38. this.sharp = require('sharp')
  39. }
  40. },
  41. /**
  42. * RESIZE IMAGE
  43. */
  44. async resize ({
  45. format = 'png',
  46. inputStream = null,
  47. inputPath = null,
  48. outputStream = null,
  49. outputPath = null,
  50. width = null,
  51. height = null,
  52. fit = 'cover',
  53. background = { r: 0, g: 0, b: 0, alpha: 0 }
  54. }) {
  55. this.load()
  56. if (inputPath) {
  57. inputStream = fs.createReadStream(inputPath)
  58. }
  59. if (!inputStream) {
  60. throw new Error('Failed to open readable input stream for image resizing.')
  61. }
  62. if (outputPath) {
  63. outputStream = fs.createWriteStream(outputPath)
  64. }
  65. if (!outputStream) {
  66. throw new Error('Failed to open writable output stream for image resizing.')
  67. }
  68. if (format === 'svg') {
  69. return pipeline([inputStream, outputStream])
  70. } else {
  71. const transformer = this.sharp().resize({
  72. width,
  73. height,
  74. fit,
  75. background
  76. }).toFormat(format)
  77. return pipeline([inputStream, transformer, outputStream])
  78. }
  79. }
  80. }