Created
June 25, 2018 16:06
-
-
Save Troland/7515cdbf65033cf788681234698b5c9e to your computer and use it in GitHub Desktop.
Copy file in node.
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
/** | |
* 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