* Allows a file to be moved (renamed) even across filesystem boundaries. * * If the rename fails because the file is getting renamed across file system boundaries, * the file is first copied to the destination file system under a temporary name, * and then renamed from there. * * This is done
(oldPath, newPath, retries = 3)
| 34 | */ |
| 35 | |
| 36 | async function safeMoveFile(oldPath, newPath, retries = 3) { |
| 37 | try { |
| 38 | // Golden path, we simply rename the file in an atomic operation |
| 39 | await fse.rename(oldPath, newPath) |
| 40 | } catch (err) { |
| 41 | // The EXDEV error indicates that the rename failed because the rename was across filesystem boundaries |
| 42 | // This might occur if a distro uses tmpfs for temporary directories |
| 43 | if (err.code === 'EXDEV') { |
| 44 | // Generate a unique destination file name to get the file onto the destination filesystem |
| 45 | const tempPath = generateTemporaryPathOnDestinationDevice(newPath) |
| 46 | |
| 47 | // Copy onto the destination filesystem (not guaranteed to be atomic) |
| 48 | await fse.copy(oldPath, tempPath) |
| 49 | // Atomically move the file onto the destination path, overwriting it |
| 50 | await fse.rename(tempPath, newPath) |
| 51 | // Delete the old file once both the above operations succeed |
| 52 | await fse.remove(oldPath) |
| 53 | } else if (err.code === 'EPERM' && retries > 0) { |
| 54 | // Windows-specific: EPERM can occur transiently file handle timing issues. |
| 55 | // Retry with exponential backoff. |
| 56 | await sleep(100 * Math.pow(2, 3 - retries)) |
| 57 | return safeMoveFile(oldPath, newPath, retries - 1) |
| 58 | } else { |
| 59 | throw err |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | export default safeMoveFile |
no test coverage detected
searching dependent graphs…