Node.js链接检查器:提取文件URL时出现空文件读取异常
核心问题根因
空文件读取的本质是Node.js异步操作链路没有做强制顺序同步,具体触发点:
fs.truncate回调内循环触发的并行fetch请求没有等待全部返回、没有等内容落盘,就直接执行后续的文件读取操作- 代码中两次定义同名
getTelescopeData函数,后定义的极简逻辑直接覆盖了原本的完整爬取流程 - 零散的
fs.appendFile调用没有状态同步,程序走到URL提取步骤时,大部分爬取内容还在网络请求的等待队列中,根本未写入磁盘 - 代码中存在无效的
console.log(err).then.process()语法,既无法实现错误终止逻辑,也会打断正常的异步链路执行。
可靠实现方案
全程用async/await语法串联所有异步步骤,把爬取、写文件、提取URL、写纯URL文件、触发链接检查的流程做严格的顺序约束:
- 先拉取所有文章列表数据,等列表数据解析完成
- 清空原始爬取存储文件,等清空操作完成
- 并行发起所有文章内容的请求,用
Promise.all等待所有文章内容全部拉取完成,把内容暂存在内存数组中,不要零散触发文件写入 - 把全部暂存的文章HTML内容一次性写入原始存储文件,等写入操作完成
- 从暂存的HTML内容中用正则匹配所有URL,做去重处理后逐行写入独立的纯URL文件,等写入完成
- 把纯URL文件的路径传入链接检查流程,启动校验。
修正后可运行代码
const fs = require('fs/promises'); const path = require('path'); // 内置链接检查逻辑,和原有规则保持一致 const _label = { good: "GOOD", bad: "BAD" }; async function runTelescopeFlow() { // 1. 拉取文章列表 const postListRes = await fetch("http://localhost:3000/posts"); const postList = await postListRes.json(); console.log(`共拉取到 ${postList.length} 篇文章记录`); // 2. 清空原始爬取内容文件 const rawContentFile = path.join(__dirname, "telescopeData_raw.html"); await fs.truncate(rawContentFile, 0); // 3. 并行拉取所有文章内容,等待全部完成 const contentPromiseList = postList.map(async (post) => { const postRes = await fetch(`http://localhost:3000${post.url}`); const postData = await postRes.json(); return postData.html; }); const allHtmlContent = await Promise.all(contentPromiseList); // 4. 一次性写入全部HTML内容,等写入完成 const rawContent = allHtmlContent.join('\n'); await fs.writeFile(rawContentFile, rawContent, 'utf-8'); console.log(`原始爬取内容已写入:${rawContentFile}`); // 5. 从HTML中提取所有URL,去重后写入纯URL文件 const urlRegex = /(http|https)(:\/\/)([\w+\-&@`~#$%^*.=/?:]+)/gi; const extractedUrls = rawContent.match(urlRegex) || []; const uniqueUrls = [...new Set(extractedUrls)]; const pureUrlFile = path.join(__dirname, "extracted_urls.txt"); await fs.writeFile(pureUrlFile, uniqueUrls.join('\n'), 'utf-8'); console.log(`共提取到 ${uniqueUrls.length} 个唯一URL,已写入纯URL文件:${pureUrlFile}`); // 6. 启动链接检查流程 await runLinkCheck(pureUrlFile); } async function runLinkCheck(targetFilePath) { const fileContent = await fs.readFile(targetFilePath, 'utf-8'); const urlList = fileContent.match(/(http|https)(:\/\/)([\w+\-&@`~#$%^*.=/?:]+)/gi) || []; for (const url of urlList) { try { const res = await fetch(url, { method: "HEAD", timeout: 2000 }); if (res.status === 200) { console.log(res.status, url, _label.good); } else if ([400, 404].includes(res.status)) { console.log(res.status, url); } } catch (error) { console.log("404", url, _label.bad); } } } // 命令行参数分支逻辑 if (process.argv.length === 2) { console.log("Hello"); } else if (process.argv[2] === "--telescope") { console.log("启动Telescope爬取流程"); runTelescopeFlow(); } else { const filePath = path.join(__dirname, process.argv[2]); runLinkCheck(filePath); } // 进程退出信号处理 process.on("SIGTERM", () => { console.log("Program is terminated"); process.exit(0); });
关键操作注意事项
- 所有文件操作统一用
fs/promises的异步版本,配合await关键字,杜绝回调嵌套导致的时序错位 - 原始HTML存储和纯URL文件完全独立存储,不会出现清空一个文件导致另一个文件被误删的问题
- URL提取操作直接从内存中暂存的HTML内容完成,不需要等磁盘文件读入内存再做匹配,进一步降低时序出错概率
- 删掉代码中无效的
.then.process()错误逻辑,统一用try/catch做错误捕获和流程终止。
内容的提问来源于stack exchange,提问作者DeveloperAndChefJenn
相关产品推荐
相关产品推荐

