Skip to content

Instantly share code, notes, and snippets.

@binki
Created August 10, 2017 19:07
Show Gist options
  • Save binki/4c0f9bf33f7ffcda273d1ce255c87bf2 to your computer and use it in GitHub Desktop.
Save binki/4c0f9bf33f7ffcda273d1ce255c87bf2 to your computer and use it in GitHub Desktop.
const fs = require('fs');
module.exports = function writeFileSafely(tempPath, destPath, contents, callback) {
fs.open(tempPath, 'w', function (err, fd) {
if (err) {
callback(err);
} else {
fs.createWriteStream(null, {
fd: fd,
autoClose: false,
}).on('error', function (err) {
fs.close(fd);
callback(err);
}).on('finish', function () {
fs.fsync(fd, function (err) {
if (err) {
callback(err);
} else {
fs.close(fd, function (err) {
if (err) {
callback(err);
} else {
fs.rename(tempPath, destPath, callback);
}
})
}
});
}).end(contents);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment