跨盘移动文件

483 阅读1分钟

1. 跨盘移动文件

Error: EXDEV: cross-device link not permitted, rename

出现 EXDEV: cross-device link not permitted 错误是因为你尝试在不同的文件系统或分区上重命名文件,这在大多数操作系统中是不允许的。

使用 fs.copyFile()fs.unlink():你可以先复制文件,然后再删除原始文件,以此来模拟 fs.rename() 的行为

const fs = require("fs");
const path = require("path");

const destinationPath = 'E:\\software_files\\EVPlayer2_download'

/**
 * 获取目录下的文件
 */
fs.readdir(path.join(__dirname, "./EVPlayer2_download"), null, async (err, files) => {
    if (err) {
        console.log(err, "---------------->err");
        return;
    }
    console.log(files, "---------------->files");

    for (const file of files) {
        await moveFile(path.join(__dirname, "./EVPlayer2_download", file), path.join(destinationPath, file))
    }

    console.log("移动文件成功了")

});

/**  
 * 移动文件
 */
const moveFile = async (source, destination) => {
    /**
     * 首先复制文件
     */

    await new Promise((resolve, reject) => {
        fs.copyFile(source, destination, (err) => {
            if (err) {
                console.error("文件复制出错:", err);
                console.error("源文件路径:", source);
                console.error("新文件路径:", destination);
                reject(err)
                return
            }
            console.log(`${source} copy success, new file path is ${destination}`);
            resolve(null)
        })
    })

    /**
     * 删除源文件
     */
    await new Promise(async (resolve, reject) => {
        fs.unlink(source, (err) => {
            if (err) {
                console.error("文件删除出错:", err);
                console.error("源文件路径:", source);
                reject(err)
                return
            }
        })
        resolve(null)
    })
}

2. rename 移动文件

const fs = require("fs");
const path = require("path");

const destinationPath = 'E:\\software_files\\EVPlayer2_download'

/**
 * 获取目录下的文件
 */
fs.readdir(path.join(__dirname, "./EVPlayer2_download"), null, async (err, files) => {
    if (err) {
        console.log(err, "---------------->err");
        return;
    }
    console.log(files, "---------------->files");

    for (const file of files) {
        await moveFile(path.join(__dirname, "./EVPlayer2_download", file), path.join(destinationPath, file))
    }

    console.log("移动文件成功了")

});

/**  
 * 移动文件
 */
const moveFile = async (source, destination) => {
    /**
     * 首先复制文件
     */

    await new Promise((resolve, reject) => {
        fs.rename(source, destination, (err) => {
            if (err) {
                console.error("文件移动出错:", err);
                console.error("源文件路径:", source);
                console.error("新文件路径:", destination);
                reject(err)
                return
            }
            console.log(`${source} copy success, new file path is ${destination}`);
            resolve(null)
        })
    })
}