Skip to content

Instantly share code, notes, and snippets.

@Troland
Created June 25, 2018 16:06
Show Gist options
  • Save Troland/7515cdbf65033cf788681234698b5c9e to your computer and use it in GitHub Desktop.
Save Troland/7515cdbf65033cf788681234698b5c9e to your computer and use it in GitHub Desktop.
Copy file in node.
/**
* Created with JetBrains WebStorm.
* User: Tristan
* Date: 14-1-21
* Time: 上午9:11
*/
var fs = require('fs');
module.exports = function move (oldPath, newPath, callback) {
fs.rename(oldPath, newPath, function(err) {
if (err) {
if (err.code === 'EXDEV') {
copy();
} else {
callback(err);
}
return;
}
callback();
});
function copy() {
var readStream = fs.createReadStream(oldPath);
var writeStream = fs.createWriteStream(newPath);
readStream.on('error', callback);
writeStream.on('error', callback);
readStream.on('close', function() {
fs.unlink(oldPath, callback);
});
readStream.pipe(writeStream);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment