You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用fs.copyFile复制文件至目录时触发EISDIR错误的求助

解决Node.js fs.copyFile触发的EISDIR错误

我尝试用Node.js的fs.copyFile复制文件,代码如下:

.then((answers) => {
    //installing dependencies in specified directory
    try{
        console.log(answers.dependencies)
        let dest = "/Users/[name]/Code/test"
        let copyingFile = fs.copyFile('/Users/[name]/Code/boilerplate/EZBOILERPLATE/testFile.js', "/Users/[name]/Code/test")
    } catch(error) {
        console.log("Error when copying file: ", error )
    }
    console.log("file coppied", copyingFile)
})

运行后触发错误:

[Error: EISDIR: illegal operation on a directory, copyfile '/Users/[name]/Code/boilerplate/EZBOILERPLATE/testFile.js' -> '/Users/[name]/Code/test'] {
  errno: -21,
  code: 'EISDIR',
  syscall: 'copyfile',
  path: '/Users/[name]/Code/boilerplate/EZBOILERPLATE/testFile.js',
  dest: '/Users/[name]/Code/test'
}

错误原因

EISDIR错误的核心是:fs.copyFile的第二个参数(目标路径)必须是具体的文件名,不能仅指定目录路径。你的代码中目标路径/Users/[name]/Code/test是目录而非文件,因此Node.js抛出“对目录执行非法操作”的错误。

此外代码还有两个隐藏问题:

  • fs.copyFile是异步方法,同步的try/catch无法捕获它的异步错误
  • 最后一行console.log("file coppied". copyingFile)存在语法错误,参数分隔应该用逗号而非点号

解决方案

1. 补全目标路径为具体文件名

直接在目标目录后拼接原文件名:

.then(async (answers) => {
    console.log(answers.dependencies)
    let dest = "/Users/[name]/Code/test/testFile.js"
    try {
        await fs.copyFile('/Users/[name]/Code/boilerplate/EZBOILERPLATE/testFile.js', dest)
        console.log("file copied")
    } catch(error) {
        console.log("Error when copying file: ", error )
    }
})

2. 用path模块动态拼接路径(推荐)

通过path模块提取原文件名并拼接到目标目录,避免硬编码:

const path = require('path');

.then(async (answers) => {
    console.log(answers.dependencies)
    const srcPath = '/Users/[name]/Code/boilerplate/EZBOILERPLATE/testFile.js';
    const destDir = "/Users/[name]/Code/test";
    // 从原路径提取文件名,拼接到目标目录
    const destPath = path.join(destDir, path.basename(srcPath));
    
    try {
        await fs.copyFile(srcPath, destPath);
        console.log("file copied");
    } catch(error) {
        console.log("Error when copying file: ", error );
    }
})

3. 回调方式处理异步操作

如果不想使用async/await,可以用回调函数捕获异步错误:

const path = require('path');

.then((answers) => {
    console.log(answers.dependencies)
    const srcPath = '/Users/[name]/Code/boilerplate/EZBOILERPLATE/testFile.js';
    const destDir = "/Users/[name]/Code/test";
    const destPath = path.join(destDir, path.basename(srcPath));
    
    fs.copyFile(srcPath, destPath, (error) => {
        if (error) {
            console.log("Error when copying file: ", error );
            return;
        }
        console.log("file copied");
    });
})

内容的提问来源于stack exchange,提问作者evan_tech1234

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 12:52:31