file.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict'
  2. const u = require('universalify').fromCallback
  3. const path = require('path')
  4. const fs = require('graceful-fs')
  5. const mkdir = require('../mkdirs')
  6. function createFile (file, callback) {
  7. function makeFile () {
  8. fs.writeFile(file, '', err => {
  9. if (err) return callback(err)
  10. callback()
  11. })
  12. }
  13. fs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err
  14. if (!err && stats.isFile()) return callback()
  15. const dir = path.dirname(file)
  16. fs.stat(dir, (err, stats) => {
  17. if (err) {
  18. // if the directory doesn't exist, make it
  19. if (err.code === 'ENOENT') {
  20. return mkdir.mkdirs(dir, err => {
  21. if (err) return callback(err)
  22. makeFile()
  23. })
  24. }
  25. return callback(err)
  26. }
  27. if (stats.isDirectory()) makeFile()
  28. else {
  29. // parent is not a directory
  30. // This is just to cause an internal ENOTDIR error to be thrown
  31. fs.readdir(dir, err => {
  32. if (err) return callback(err)
  33. })
  34. }
  35. })
  36. })
  37. }
  38. function createFileSync (file) {
  39. let stats
  40. try {
  41. stats = fs.statSync(file)
  42. } catch {}
  43. if (stats && stats.isFile()) return
  44. const dir = path.dirname(file)
  45. try {
  46. if (!fs.statSync(dir).isDirectory()) {
  47. // parent is not a directory
  48. // This is just to cause an internal ENOTDIR error to be thrown
  49. fs.readdirSync(dir)
  50. }
  51. } catch (err) {
  52. // If the stat call above failed because the directory doesn't exist, create it
  53. if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir)
  54. else throw err
  55. }
  56. fs.writeFileSync(file, '')
  57. }
  58. module.exports = {
  59. createFile: u(createFile),
  60. createFileSync
  61. }