Guest User

Untitled

a guest
Dec 16th, 2017
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. async function copyFile(src, dest) {
  2. const readStream = fs.createReadStream(src)
  3. const writeStream = fs.createWriteStream(dest, { flags: 'wx' })
  4. const errors = ['EISDIR', 'EACCES','EEXIST']
  5.  
  6. readStream.on('error', err => {
  7. if (err.code === 'EISDIR') {
  8. console.log(`Source ${src} is a directory`)
  9. }
  10.  
  11. if (err.code === 'EACCES') {
  12. console.log(`Can not read the source ${src} due to lack of permissions`)
  13. }
  14.  
  15. if (err.code === 'ENOENT') {
  16. console.log(`Source file ${src} is absent`)
  17. }
  18.  
  19. writeStream.destroy()
  20.  
  21. fs.remove(dest).catch(err => console.log(err))
  22. })
  23.  
  24. writeStream.on('error', err => {
  25. if (err.code === 'EISDIR') {
  26. console.log(`Source ${src} is a directory`)
  27. }
  28.  
  29. if (err.code === 'EACCES') {
  30. console.log(`Can not write to destination ${dest} due to lack of permissions`)
  31. }
  32.  
  33. if (err.code === 'EEXIST') {
  34. console.log(`Destination file ${src} already present`)
  35. }
  36.  
  37. readStream.destroy()
  38.  
  39. if (!errors.indexOf(err.code) > -1) {
  40. fs.remove(dest).catch(err => console.log(err))
  41. }
  42. })
  43.  
  44. readStream.pipe(writeStream)
  45. }
Add Comment
Please, Sign In to add comment