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

Node.js终端中fs.copyFile无法运行的问题求助

Node.js fs.copyFile 报错:ERR_INVALID_ARG_TYPE 解决方法

问题场景

使用Node.js复制文件时,运行以下代码:

const fs = require('fs');
fs.copyFile('file1.txt', 'file2.txt');

执行node index.js后抛出错误,错误信息如下:

node: internal/validators:421
throw new ERR_INVALID_ARG_TYPE(name,
'Function', value);
MINGW64:/c/Users/HP/Desktop/intro-to-node

TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined
at makeCallback (node:fs:195:3)
at Object.copyFile (node:fs:2841:14)
at Object. ‹anonymous› (C: \Users\HP\Desktop\intro-to-node\index.js:4:4) at Module,_compile (node: internal/modules/cjs/loader: 1218:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Module.load (node: internal/modules/cjs/loader:1081:32)
at Module._load (node: internal/modules/cjs/loader:922:12)
at Function.executeUserEntryPoint [as runMain] (node: internal/modules/run_main:81:12)
at node: internal/main/run_main_module:23:47 {
code: 'ERR_INVALID_ARG_TYPE'
}
Node.js v18.13.0

错误原因

异步版本的fs.copyFile必须传入第三个参数作为回调函数,用于处理复制完成或错误的情况。你的代码中缺少这个回调参数,导致Node.js抛出类型错误。这和Node.js版本无关,v18.13.0完全支持该API。

解决方案

提供三种可行的实现方式:

1. 传入回调函数(异步模式)

给fs.copyFile添加回调函数,处理复制结果:

const fs = require('fs');

fs.copyFile('file1.txt', 'file2.txt', (err) => {
  if (err) {
    console.error('文件复制失败:', err);
    return;
  }
  console.log('文件复制成功');
});

2. 使用同步版本fs.copyFileSync

如果不需要异步操作,直接用同步方法,无需回调:

const fs = require('fs');

try {
  fs.copyFileSync('file1.txt', 'file2.txt');
  console.log('文件复制成功');
} catch (err) {
  console.error('文件复制失败:', err);
}

3. 使用Promise风格API(fs.promises)

Node.js 10及以上版本支持Promise风格的文件操作,可配合async/await或.then()使用:

const fs = require('fs').promises;

// 方式1: async/await
async function copyFile() {
  try {
    await fs.copyFile('file1.txt', 'file2.txt');
    console.log('文件复制成功');
  } catch (err) {
    console.error('文件复制失败:', err);
  }
}

copyFile();

// 方式2: .then()链式调用
fs.copyFile('file1.txt', 'file2.txt')
  .then(() => console.log('文件复制成功'))
  .catch(err => console.error('文件复制失败:', err));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:30:52