Created
August 10, 2017 19:07
-
-
Save binki/4c0f9bf33f7ffcda273d1ce255c87bf2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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