ext.js 2.2 KB

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