util.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. const util = require('util')
  2. const path = require('path')
  3. const fs = require('fs')
  4. const readFile = util.promisify(fs.readFile)
  5. const writeFile = util.promisify(fs.writeFile)
  6. const copyFile = util.promisify(fs.copyFile)
  7. const fileExists = util.promisify(fs.exists)
  8. const mkdirp = util.promisify(require('mkdirp'))
  9. const concurrently = require('concurrently')
  10. const { watch } = require('gulp')
  11. exports.watch = betterWatch
  12. exports.watchTask = watchTask
  13. exports.shellTask = shellTask
  14. exports.promisifyVinyl = promisifyVinyl
  15. exports.readFile = betterReadFile
  16. exports.writeFile = betterWriteFile
  17. exports.writeFileSync = betterWriteFileSync
  18. exports.copyFile = betterCopyFile
  19. exports.fileExists = fileExists
  20. exports.mkdirp = mkdirp
  21. function betterWatch() {
  22. let watcher = watch.apply(null, arguments)
  23. return new Promise((resolve) => {
  24. process.on('SIGINT', function() {
  25. watcher.close()
  26. resolve()
  27. })
  28. })
  29. }
  30. function watchTask() { // TODO: use in more places
  31. let watchArgs = arguments
  32. return function() {
  33. return betterWatch.apply(null, watchArgs)
  34. }
  35. }
  36. function shellTask(...tasks) {
  37. let func = function() {
  38. return concurrently(tasks) // good for labeling each line of output
  39. }
  40. func.displayName = tasks.join(' ')
  41. return func
  42. }
  43. /*
  44. turns a vinyl stream object into a promise
  45. */
  46. function promisifyVinyl(vinyl) {
  47. return new Promise(function(resolve, reject) {
  48. vinyl.on('end', resolve) // TODO: handle error?
  49. })
  50. }
  51. function betterReadFile(destPath) {
  52. return readFile(destPath, { encoding: 'utf8' })
  53. }
  54. function betterWriteFile(destPath, content) {
  55. return mkdirp(path.dirname(destPath)).then(function() {
  56. return writeFile(destPath, content, { encoding: 'utf8' })
  57. })
  58. }
  59. function betterWriteFileSync(destPath, content) {
  60. mkdirp.sync(path.dirname(destPath))
  61. writeFile(destPath, content, { encoding: 'utf8' })
  62. }
  63. function betterCopyFile(srcPath, destPath) {
  64. return mkdirp(path.dirname(destPath)).then(function() {
  65. return copyFile(srcPath, destPath)
  66. })
  67. }