[英]Javascript - Moving Files between Directories
我有一個名為“已接收”的文件夾,還有另外兩個名為“成功”和“錯誤”的文件夾。 所有新文件都將存儲在“已接收”文件夾中,並在存儲在所述文件夾中后,將由我的系統處理。 成功解析的文件將移至“成功”文件夾,而所有有問題的文件將存儲在“錯誤”文件夾中。
我主要關心的是基本上在目錄之間移動文件。
我已經試過了:
// oldPath = Received Folder
// sucsPath = Successful Folder
// failPath = Error Folder
// Checks if Successful or fail. 1 = Success; 0 = Fail
if(STATUS == '1') { // 1 = Success;
fs.rename(oldPath, sucsPath, function (err) {
if (err) {
if (err.code === 'EXDEV') {
var readStream = fs.createReadStream(oldPath);
var writeStream = fs.createWriteStream(sucsPath);
readStream.on('error', callback);
writeStream.on('error', callback);
readStream.on('close', function () {
fs.unlink(oldPath, callback);
});
readStream.pipe(writeStream);
}
else {
callback(err);
}
return;
}
callback();
});
}
else { // 0 = Fail
fs.rename(oldPath, failPath, function (err) {
if (err) {
if (err.code === 'EXDEV') {
var readStream = fs.createReadStream(oldPath);
var writeStream = fs.createWriteStream(failPath);
readStream.on('error', callback);
writeStream.on('error', callback);
readStream.on('close', function () {
fs.unlink(oldPath, callback);
});
readStream.pipe(writeStream);
}
else {
callback(err);
}
return;
}
callback();
});
}
但是,我擔心的是它會刪除原始文件夾,並將所有文件傳遞到指定的文件夾中。 我相信代碼中的邏輯是,它從字面上重命名了文件(包括目錄)。 我還遇到了“ await moveFile”,但是基本上它做同樣的事情。
我只想通過簡單地指定文件名,文件的來源及其目的地在目錄之間移動文件。
如rufus1530所述,我使用了以下方法:
fs.createReadStream(origin).pipe(fs.createWriteStream(destination));
下一步是刪除文件。
我用這個:
fs.unlinkSync(file);
從8.5開始,您擁有fs.copyFile
,這是復制文件的最簡單方法。
因此,您將創建自己的移動函數,該函數將首先嘗試重命名,然后嘗試復制。
const util = require('util')
const copyFile = util.promisify(fs.copyFile)
const rename = util.promisify(fs.rename)
const unlink = util.promisify(fs.unlink)
const path = require('path')
async function moveFileTo(file, dest) {
// get the file name of the path
const fileName = path.basename(file)
// combine the path of destination directory and the filename
const destPath = path.join(dest, fileName)
try {
await fs.rename(file, destPath)
} catch( err ) {
if (err.code === 'EXDEV') {
// we need to copy if the destination is on another parition
await copyFile(file, destPath)
// delete the old file if copying was successful
await unlink(file)
} else {
// re throw the error if it is another error
throw err
}
}
}
然后,您可以使用它來await moveFileTo('/path/to/file.txt', '/new/path')
,它將把/path/to/file.txt
移動到/new/path/file.txt
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.