module.exports.sync = function writeFileSync (filename, data, options) { if (!options) options = {} var tmpfile = getTmpname(filename) try { if (!options.mode || !options.chmod) { // Either mode or chown is not explicitly set // Default behavior is to copy it from original file try { var stats = fs.statSync(filename) options = extend({}, options) if (!options.mode) { options.mode = stats.mode } if (!options.chown && process.getuid) { options.chown = { uid: stats.uid, gid: stats.gid } } } catch (ex) { // ignore stat errors } } fs.writeFileSync(tmpfile, data, options.encoding || 'utf8') if (options.chown) fs.chownSync(tmpfile, options.chown.uid, options.chown.gid) if (options.mode) fs.chmodSync(tmpfile, options.mode) fs.renameSync(tmpfile, filename) } catch (err) { try { fs.unlinkSync(tmpfile) } catch (e) {} throw err } }
function writeFileSync (filename, data, options) { if (typeof options === 'string') options = { encoding: options } else if (!options) options = {} try { filename = fs.realpathSync(filename) } catch (ex) { // it's ok, it'll happen on a not yet existing file } var tmpfile = getTmpname(filename) if (!options.mode || !options.chown) { // Either mode or chown is not explicitly set // Default behavior is to copy it from original file try { var stats = fs.statSync(filename) options = Object.assign({}, options) if (!options.mode) { options.mode = stats.mode } if (!options.chown && process.getuid) { options.chown = { uid: stats.uid, gid: stats.gid } } } catch (ex) { // ignore stat errors } } var fd var cleanup = cleanupOnExit(tmpfile) var removeOnExitHandler = onExit(cleanup) try { fd = fs.openSync(tmpfile, 'w', options.mode) if (Buffer.isBuffer(data)) { fs.writeSync(fd, data, 0, data.length, 0) } else if (data != null) { fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8')) } if (options.fsync !== false) { fs.fsyncSync(fd) } fs.closeSync(fd) if (options.chown) fs.chownSync(tmpfile, options.chown.uid, options.chown.gid) if (options.mode) fs.chmodSync(tmpfile, options.mode) fs.renameSync(tmpfile, filename) removeOnExitHandler() } catch (err) { if (fd) fs.closeSync(fd) removeOnExitHandler() cleanup() throw err } }
module.exports.sync = function writeFileSync(filename, data, options) { if (!options) options = {}; var tmpfile = getTmpname(filename); try { fs.writeFileSync(tmpfile, data, options); if (options.chown) fs.chownSync(tmpfile, options.chown.uid, options.chown.gid); fs.renameSync(tmpfile, filename); } catch (err) { try { fs.unlinkSync(tmpfile) } catch(e) {} throw err; } }