Node.js TypeError [ERR_INVALID_ARG_TYPE]错误修复求助
解决Node.js写入文件的TypeError错误
错误根源
- 读取
count.txt时,若文件为空或无有效数字内容,parseInt(count)会返回NaN,而writeFileSync不接受数字类型参数(包括NaN),直接触发类型错误。 - 之前用
toString()出现字符串拼接,是因为没先把读取到的字符串转成有效数字就做加法,导致字符串与数字直接拼接(比如"1"+1变成"11")。
修改后的完整代码
const { readFileSync, writeFileSync } = require('fs'); const express = require('express'); const app = express(); app.get('/', (req, res) => { // 读取计数文件,处理空值/非数字场景,默认初始计数为0 const countStr = readFileSync('./count.txt', 'utf-8'); const count = parseInt(countStr, 10) || 0; console.log('当前计数:', count); // 确保是数字运算,得到新计数 const newCount = count + 1; // 将数字转为字符串后写入文件,满足writeFileSync的参数类型要求 writeFileSync('./count.txt', newCount.toString()); // 返回期望的HTML页面内容 res.send(` <h1>Welcome to my Website!</h1> <h1>This site has been viewed ${newCount} times</h1> `); }); // 启动服务器,监听3000端口 app.listen(3000, () => { console.log('服务器运行在 http://localhost:3000'); });
核心修改说明
parseInt(countStr, 10) || 0:指定十进制解析避免进制问题,同时给无效内容设置默认值0,保证计数始终是有效数字。newCount.toString():把数字类型的计数转为字符串,符合writeFileSync对写入数据的类型要求,解决TypeError。- 补充
res.send()返回HTML代码,实现页面显示欢迎语和访问次数的需求。
内容的提问来源于stack exchange,提问作者H.Finn
相关产品推荐
相关产品推荐

