index.js 6.6 KB

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