2 module.exports = writeFile
3 module.exports.sync = writeFileSync
4 module.exports._getTmpname = getTmpname // for testing
5 module.exports._cleanupOnExit = cleanupOnExit
7 var fs = require('graceful-fs')
8 var MurmurHash3 = require('imurmurhash')
9 var onExit = require('signal-exit')
10 var path = require('path')
13 // if we run inside of a worker_thread, `process.pid` is not unique
14 /* istanbul ignore next */
15 var threadId = (function getId () {
17 var workerThreads = require('worker_threads')
19 /// if we are in main thread, this is set to `0`
20 return workerThreads.threadId
22 // worker_threads are not available, fallback to 0
28 function getTmpname (filename) {
29 return filename + '.' +
30 MurmurHash3(__filename)
31 .hash(String(process.pid))
32 .hash(String(threadId))
33 .hash(String(++invocations))
37 function cleanupOnExit (tmpfile) {
40 fs.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile)
45 function writeFile (filename, data, options, callback) {
47 if (options instanceof Function) {
50 } else if (typeof options === 'string') {
51 options = { encoding: options }
57 var Promise = options.Promise || global.Promise
61 /* istanbul ignore next -- The closure only gets called when onExit triggers */
62 var removeOnExitHandler = onExit(cleanupOnExit(() => tmpfile))
63 var absoluteName = path.resolve(filename)
65 new Promise(function serializeSameFile (resolve) {
66 // make a queue if it doesn't already exist
67 if (!activeFiles[absoluteName]) activeFiles[absoluteName] = []
69 activeFiles[absoluteName].push(resolve) // add this job to the queue
70 if (activeFiles[absoluteName].length === 1) resolve() // kick off the first one
71 }).then(function getRealPath () {
72 return new Promise(function (resolve) {
73 fs.realpath(filename, function (_, realname) {
74 truename = realname || filename
75 tmpfile = getTmpname(truename)
79 }).then(function stat () {
80 return new Promise(function stat (resolve) {
81 if (options.mode && options.chown) resolve()
83 // Either mode or chown is not explicitly set
84 // Default behavior is to copy it from original file
85 fs.stat(truename, function (err, stats) {
86 if (err || !stats) resolve()
88 options = Object.assign({}, options)
90 if (options.mode == null) {
91 options.mode = stats.mode
93 if (options.chown == null && process.getuid) {
94 options.chown = { uid: stats.uid, gid: stats.gid }
101 }).then(function thenWriteFile () {
102 return new Promise(function (resolve, reject) {
103 fs.open(tmpfile, 'w', options.mode, function (err, _fd) {
109 }).then(function write () {
110 return new Promise(function (resolve, reject) {
111 if (Buffer.isBuffer(data)) {
112 fs.write(fd, data, 0, data.length, 0, function (err) {
116 } else if (data != null) {
117 fs.write(fd, String(data), 0, String(options.encoding || 'utf8'), function (err) {
123 }).then(function syncAndClose () {
124 return new Promise(function (resolve, reject) {
125 if (options.fsync !== false) {
126 fs.fsync(fd, function (err) {
127 if (err) fs.close(fd, () => reject(err))
128 else fs.close(fd, resolve)
131 fs.close(fd, resolve)
134 }).then(function chown () {
137 return new Promise(function (resolve, reject) {
138 fs.chown(tmpfile, options.chown.uid, options.chown.gid, function (err) {
144 }).then(function chmod () {
146 return new Promise(function (resolve, reject) {
147 fs.chmod(tmpfile, options.mode, function (err) {
153 }).then(function rename () {
154 return new Promise(function (resolve, reject) {
155 fs.rename(tmpfile, truename, function (err) {
160 }).then(function success () {
161 removeOnExitHandler()
163 }, function fail (err) {
164 return new Promise(resolve => {
165 return fd ? fs.close(fd, resolve) : resolve()
167 removeOnExitHandler()
168 fs.unlink(tmpfile, function () {
172 }).then(function checkQueue () {
173 activeFiles[absoluteName].shift() // remove the element added by serializeSameFile
174 if (activeFiles[absoluteName].length > 0) {
175 activeFiles[absoluteName][0]() // start next job if one is pending
176 } else delete activeFiles[absoluteName]
180 function writeFileSync (filename, data, options) {
181 if (typeof options === 'string') options = { encoding: options }
182 else if (!options) options = {}
184 filename = fs.realpathSync(filename)
186 // it's ok, it'll happen on a not yet existing file
188 var tmpfile = getTmpname(filename)
190 if (!options.mode || !options.chown) {
191 // Either mode or chown is not explicitly set
192 // Default behavior is to copy it from original file
194 var stats = fs.statSync(filename)
195 options = Object.assign({}, options)
197 options.mode = stats.mode
199 if (!options.chown && process.getuid) {
200 options.chown = { uid: stats.uid, gid: stats.gid }
203 // ignore stat errors
208 var cleanup = cleanupOnExit(tmpfile)
209 var removeOnExitHandler = onExit(cleanup)
212 fd = fs.openSync(tmpfile, 'w', options.mode)
213 if (Buffer.isBuffer(data)) {
214 fs.writeSync(fd, data, 0, data.length, 0)
215 } else if (data != null) {
216 fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8'))
218 if (options.fsync !== false) {
222 if (options.chown) fs.chownSync(tmpfile, options.chown.uid, options.chown.gid)
223 if (options.mode) fs.chmodSync(tmpfile, options.mode)
224 fs.renameSync(tmpfile, filename)
225 removeOnExitHandler()
231 // ignore close errors at this stage, error may have closed fd already.
234 removeOnExitHandler()