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

如何修复TypeError: Cannot read properties of undefined (reading 'pipe')错误

Node.js 流操作报错解决:TypeError: Cannot read properties of undefined (reading 'pipe')

问题原因

你的代码存在两处关键拼写错误,同时需考虑文件存在性问题:

  • 函数定义名称为readAndwrite(小写w),但导出时写成readAndWrite(大写W),导致导出的是未定义变量,调用时触发错误
  • 控制台日志里的文件名拼写错误:duplciate.txt应为duplicate.txt
  • 额外注意:若input.txt不存在,createReadStream会触发error事件,也可能引发后续操作异常

修复后的代码

var fs = require('fs');

function readAndWrite() {
  var readableStream = fs.createReadStream('input.txt');
  var writeableStream = fs.createWriteStream('duplicate.txt');
  
  // 监听读取流错误,避免程序崩溃
  readableStream.on('error', (err) => {
    console.error('读取文件出错:', err.message);
  });
  
  readableStream.pipe(writeableStream);
  
  // 流复制完成后再打印提示,更准确
  writeableStream.on('finish', () => {
    console.log("内容已复制到 duplicate.txt");
  });
}

module.exports.readAndWrite = readAndWrite;

额外建议

  • 确保input.txt与app.js在同一目录,或使用完整文件路径
  • 流操作是异步的,原代码会在复制开始时就打印提示,监听finish事件能保证提示在复制完成后输出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 02:33:18