Node.js执行报错:TypeError: add is not a function 求助排查
问题排查与解决
核心错误点
- 导出语法错误:
functions.js里的导出语句写错了,Node.js的CommonJS导出语法是module.exports,你写成了module.export(缺少末尾的s),导致导出内容不是函数,进而在调用时触发TypeError。 - 文件运行逻辑混乱:你执行命令
node index.js functions.js,但报错的是index.cjs,说明文件名存在混淆;同时index.js包含浏览器DOM操作代码(document.getElementById),Node.js环境没有DOM API,直接运行会额外报错。
分步修复
1. 修复functions.js的导出语法
修改functions.js的导出代码:
//const readlineSync = require (readlineSync) module.exports = function add(a,b) { return a + b }
2. 正确导入并调用函数
如果测试add函数的入口是index.cjs,调整导入逻辑:
const add = require('./functions'); console.log(add(20,30)); // 现在可正常调用 // 注意:DOM操作代码不能在Node.js环境执行,需拆分到浏览器专属脚本中
3. 拆分浏览器与Node.js代码
把DOM操作代码单独放在浏览器端的index.js中:
const inputFieldEl = document.getElementById("input-field") const addButtonEl = document.getElementById("add-button") addButtonEl.addEventListener("click", function() { let inputValue = inputFieldEl.value console.log(`${inputValue} added to database`) })
4. 正确运行Node.js测试代码
测试add函数时,直接运行对应Node.js文件即可,无需传入多个文件:
node index.cjs
额外补充(浏览器端模块使用)
如果需要在浏览器中通过ES模块引入add函数,可修改functions.js为ES导出:
export function add(a,b) { return a + b }
然后在index.js中导入:
import { add } from './functions.js'; // 可在浏览器环境中调用add函数
内容的提问来源于stack exchange,提问作者Learning corner
相关产品推荐
相关产品推荐

