如何编写无需第三方库的Node.js下载application/text头文件最简脚本
问题:编写无第三方依赖的Node.js最简下载脚本
现有Next.js路由响应代码
该接口返回application/text类型的文本内容:
const data = 'abba dabba jabba' return new Response(data, { headers: { 'content-type': 'application/text' }, })
当前使用的下载脚本(含第三方依赖)
目前的脚本依赖consola第三方日志库,代码如下:
import fs from 'fs' import { consola } from 'consola' const LOCALHOST_URL = 'http://localhost:3000' async function main() { for (let i = 0; i < 5; i++) { const url = `${LOCALHOST_URL}/api/download` const fingerprint = 'anon' const body = JSON.stringify({ fingerprint }) const response = await fetch(url, { method: 'POST', body, }) const buffer = await response.arrayBuffer() fs.writeFileSync(`file${i}.txt`, buffer) } } main()
需求
编写无需任何第三方库的最简Node.js脚本,实现下载上述接口返回的文本内容,且必须保留发送fingerprint参数的逻辑。
最简实现脚本
以下是完全基于Node.js原生API的实现(要求Node.js版本18+,原生支持fetch):
import fs from 'fs'; const LOCALHOST_URL = 'http://localhost:3000'; async function main() { for (let i = 0; i < 5; i++) { const url = `${LOCALHOST_URL}/api/download`; const fingerprint = 'anon'; const body = JSON.stringify({ fingerprint }); // 发送POST请求,携带fingerprint参数 const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' // 必须添加,告知接口请求体为JSON格式 }, body, }); // 检查请求是否成功 if (!response.ok) { throw new Error(`请求接口失败,状态码: ${response.status}`); } // 直接获取文本内容(适配application/text类型) const textContent = await response.text(); // 写入本地文件 fs.writeFileSync(`file${i}.txt`, textContent, 'utf8'); console.log(`文件已保存: file${i}.txt`); } } // 捕获执行过程中的错误 main().catch(err => console.error('下载过程出错:', err));
关键优化说明
- 移除第三方依赖:删掉了
consola,用原生console.log和console.error处理日志与错误 - 补充必要请求头:添加
Content-Type: application/json,确保接口能正确解析JSON格式的请求体 - 优化内容处理:用
response.text()直接获取文本内容,比arrayBuffer()更适配application/text类型的响应 - 增加错误处理:检查响应状态、捕获全局错误,避免脚本无提示崩溃
内容的提问来源于stack exchange,提问作者deadcoder0904
相关产品推荐
相关产品推荐

