异常
当使用fs
模块的renameSync()
方法时报错如下:
Error: EXDEV: cross-device link not permitted, rename 'F:\trash.conf' -> 'G:\Trash\trash.conf'
?[90m at Object.renameSync (node:fs:980:3)?[39m
at Object.<anonymous> (F:\Pre_Coding\Pre_WebStorm_Project\linux-trash-nodejs\trash.js:31:25)
?[90m at Module._compile (node:internal/modules/cjs/loader:1097:14)?[39m
?[90m at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)?[39m
?[90m at Module.load (node:internal/modules/cjs/loader:975:32)?[39m
?[90m at Function.Module._load (node:internal/modules/cjs/loader:822:12)?[39m
?[90m at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)?[39m
?[90m at node:internal/main/run_main_module:17:47?[39m {
errno: ?[33m-4037?[39m,
syscall: ?[32m'rename'?[39m,
code: ?[32m'EXDEV'?[39m,
path: ?[32m'F:\trash.conf'?[39m,
dest: ?[32m'G:\Trash\trash.conf'?[39m
}
Node.js v17.1.0
错误代码
var fs = require('fs');
fs.renameSync('F:\trash.conf', 'G:\Trash\trash.conf');
原因
这是跨区重命名文件出现的权限问题,错误代码中从F
盘剪切文件到G
盘属于跨区。
解决
先将源文件拷贝到另外分区的目标文件,然后再使用unlink
删除源文件。
正确代码
var fs = require('fs');
var deletedFilePath = 'F:\trash.conf';
var trashFilePath = 'G:\Trash\trash.conf';
var rs = fs.createReadStream(deletedFilePath);
var ws = fs.createWriteStream(trashFilePath);
rs.pipe(ws);
rs.on('end', function () {
fs.unlinkSync(deletedFilePath);
});