file.js 1.4 KB

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