Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. 'use strict'
  2. module.exports = writeFile
  3. module.exports.sync = writeFileSync
  4. module.exports._getTmpname = getTmpname // for testing
  5. module.exports._cleanupOnExit = cleanupOnExit
  6. const fs = require('fs')
  7. const MurmurHash3 = require('imurmurhash')
  8. const onExit = require('signal-exit')
  9. const path = require('path')
  10. const isTypedArray = require('is-typedarray')
  11. const typedArrayToBuffer = require('typedarray-to-buffer')
  12. const { promisify } = require('util')
  13. const activeFiles = {}
  14. // if we run inside of a worker_thread, `process.pid` is not unique
  15. /* istanbul ignore next */
  16. const threadId = (function getId () {
  17. try {
  18. const workerThreads = require('worker_threads')
  19. /// if we are in main thread, this is set to `0`
  20. return workerThreads.threadId
  21. } catch (e) {
  22. // worker_threads are not available, fallback to 0
  23. return 0
  24. }
  25. })()
  26. let invocations = 0
  27. function getTmpname (filename) {
  28. return filename + '.' +
  29. MurmurHash3(__filename)
  30. .hash(String(process.pid))
  31. .hash(String(threadId))
  32. .hash(String(++invocations))
  33. .result()
  34. }
  35. function cleanupOnExit (tmpfile) {
  36. return () => {
  37. try {
  38. fs.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile)
  39. } catch (_) {}
  40. }
  41. }
  42. function serializeActiveFile (absoluteName) {
  43. return new Promise(resolve => {
  44. // make a queue if it doesn't already exist
  45. if (!activeFiles[absoluteName]) activeFiles[absoluteName] = []
  46. activeFiles[absoluteName].push(resolve) // add this job to the queue
  47. if (activeFiles[absoluteName].length === 1) resolve() // kick off the first one
  48. })
  49. }
  50. // https://github.com/isaacs/node-graceful-fs/blob/master/polyfills.js#L315-L342
  51. function isChownErrOk (err) {
  52. if (err.code === 'ENOSYS') {
  53. return true
  54. }
  55. const nonroot = !process.getuid || process.getuid() !== 0
  56. if (nonroot) {
  57. if (err.code === 'EINVAL' || err.code === 'EPERM') {
  58. return true
  59. }
  60. }
  61. return false
  62. }
  63. async function writeFileAsync (filename, data, options = {}) {
  64. if (typeof options === 'string') {
  65. options = { encoding: options }
  66. }
  67. let fd
  68. let tmpfile
  69. /* istanbul ignore next -- The closure only gets called when onExit triggers */
  70. const removeOnExitHandler = onExit(cleanupOnExit(() => tmpfile))
  71. const absoluteName = path.resolve(filename)
  72. try {
  73. await serializeActiveFile(absoluteName)
  74. const truename = await promisify(fs.realpath)(filename).catch(() => filename)
  75. tmpfile = getTmpname(truename)
  76. if (!options.mode || !options.chown) {
  77. // Either mode or chown is not explicitly set
  78. // Default behavior is to copy it from original file
  79. const stats = await promisify(fs.stat)(truename).catch(() => {})
  80. if (stats) {
  81. if (options.mode == null) {
  82. options.mode = stats.mode
  83. }
  84. if (options.chown == null && process.getuid) {
  85. options.chown = { uid: stats.uid, gid: stats.gid }
  86. }
  87. }
  88. }
  89. fd = await promisify(fs.open)(tmpfile, 'w', options.mode)
  90. if (options.tmpfileCreated) {
  91. await options.tmpfileCreated(tmpfile)
  92. }
  93. if (isTypedArray(data)) {
  94. data = typedArrayToBuffer(data)
  95. }
  96. if (Buffer.isBuffer(data)) {
  97. await promisify(fs.write)(fd, data, 0, data.length, 0)
  98. } else if (data != null) {
  99. await promisify(fs.write)(fd, String(data), 0, String(options.encoding || 'utf8'))
  100. }
  101. if (options.fsync !== false) {
  102. await promisify(fs.fsync)(fd)
  103. }
  104. await promisify(fs.close)(fd)
  105. fd = null
  106. if (options.chown) {
  107. await promisify(fs.chown)(tmpfile, options.chown.uid, options.chown.gid).catch(err => {
  108. if (!isChownErrOk(err)) {
  109. throw err
  110. }
  111. })
  112. }
  113. if (options.mode) {
  114. await promisify(fs.chmod)(tmpfile, options.mode).catch(err => {
  115. if (!isChownErrOk(err)) {
  116. throw err
  117. }
  118. })
  119. }
  120. await promisify(fs.rename)(tmpfile, truename)
  121. } finally {
  122. if (fd) {
  123. await promisify(fs.close)(fd).catch(
  124. /* istanbul ignore next */
  125. () => {}
  126. )
  127. }
  128. removeOnExitHandler()
  129. await promisify(fs.unlink)(tmpfile).catch(() => {})
  130. activeFiles[absoluteName].shift() // remove the element added by serializeSameFile
  131. if (activeFiles[absoluteName].length > 0) {
  132. activeFiles[absoluteName][0]() // start next job if one is pending
  133. } else delete activeFiles[absoluteName]
  134. }
  135. }
  136. function writeFile (filename, data, options, callback) {
  137. if (options instanceof Function) {
  138. callback = options
  139. options = {}
  140. }
  141. const promise = writeFileAsync(filename, data, options)
  142. if (callback) {
  143. promise.then(callback, callback)
  144. }
  145. return promise
  146. }
  147. function writeFileSync (filename, data, options) {
  148. if (typeof options === 'string') options = { encoding: options }
  149. else if (!options) options = {}
  150. try {
  151. filename = fs.realpathSync(filename)
  152. } catch (ex) {
  153. // it's ok, it'll happen on a not yet existing file
  154. }
  155. const tmpfile = getTmpname(filename)
  156. if (!options.mode || !options.chown) {
  157. // Either mode or chown is not explicitly set
  158. // Default behavior is to copy it from original file
  159. try {
  160. const stats = fs.statSync(filename)
  161. options = Object.assign({}, options)
  162. if (!options.mode) {
  163. options.mode = stats.mode
  164. }
  165. if (!options.chown && process.getuid) {
  166. options.chown = { uid: stats.uid, gid: stats.gid }
  167. }
  168. } catch (ex) {
  169. // ignore stat errors
  170. }
  171. }
  172. let fd
  173. const cleanup = cleanupOnExit(tmpfile)
  174. const removeOnExitHandler = onExit(cleanup)
  175. let threw = true
  176. try {
  177. fd = fs.openSync(tmpfile, 'w', options.mode || 0o666)
  178. if (options.tmpfileCreated) {
  179. options.tmpfileCreated(tmpfile)
  180. }
  181. if (isTypedArray(data)) {
  182. data = typedArrayToBuffer(data)
  183. }
  184. if (Buffer.isBuffer(data)) {
  185. fs.writeSync(fd, data, 0, data.length, 0)
  186. } else if (data != null) {
  187. fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8'))
  188. }
  189. if (options.fsync !== false) {
  190. fs.fsyncSync(fd)
  191. }
  192. fs.closeSync(fd)
  193. fd = null
  194. if (options.chown) {
  195. try {
  196. fs.chownSync(tmpfile, options.chown.uid, options.chown.gid)
  197. } catch (err) {
  198. if (!isChownErrOk(err)) {
  199. throw err
  200. }
  201. }
  202. }
  203. if (options.mode) {
  204. try {
  205. fs.chmodSync(tmpfile, options.mode)
  206. } catch (err) {
  207. if (!isChownErrOk(err)) {
  208. throw err
  209. }
  210. }
  211. }
  212. fs.renameSync(tmpfile, filename)
  213. threw = false
  214. } finally {
  215. if (fd) {
  216. try {
  217. fs.closeSync(fd)
  218. } catch (ex) {
  219. // ignore close errors at this stage, error may have closed fd already.
  220. }
  221. }
  222. removeOnExitHandler()
  223. if (threw) {
  224. cleanup()
  225. }
  226. }
  227. }