javascript - node.js如何使用fs来接收get api结果
问题描述
我是 node.js 的新手。在这里,我正在尝试使用收到的结果(response.body)创建一个 txt 文件。但它只是打印一个异常。需要你的帮助。
function fetch(){
const got = require('got');
got('https://www.google.com', { json: true }).then(response => {
console.log(response.body);
temp = response.body;
}).catch(error => {
console.log(error.response.body);
});
};
setInterval(fetch, 10000);
const fs = require('fs');
fs.write('demo3.txt', response.body, { flag: "a"}, function(err){
if(err){
return console.log(err);
}
});
解决方案
由于您是 nodeJS 的新手,因此您需要了解回调函数的概念。这里的'got'是一个回调函数。与其他类型的脚本不同,NodeJs 不会等待 fetch 完成,而是继续前进并执行剩余的语句。您的代码有一些错误。
变量“temp”、“response”的范围。-- 在执行 fs.write 时,response.body 保持未定义和未声明。由于 fetch 功能尚未执行。
您发送了一个参数 { json: true },该参数尝试获取 JSON 格式的响应。但请求的 URL 以普通文本文档/HTML 文档回复。因此,删除该参数肯定会有所帮助。
const fs = require('fs'); const got = require('got'); function fetch(){ got('https://www.google.com' ).then(response => { console.log("Response"); temp = response.body; fs.writeFile('demo3.txt', temp , { flag: "a"}, function(err){ if(err){ return console.log(err); } }); }).catch(error => { console.log(error); }); }; fetch();
这里 fs.write 将在“got”函数通过返回响应变量完成其执行后执行。在这里,我还删除了参数 { json: true } ,因为响应不是 JSON 格式。
推荐阅读
- python - 如何获得查询匹配次数的计数
- python - AWS IoT - 创建 lambda 循环以提供交替的模拟结果
- java - 将 java 项目导出到 jar 更改了访问修饰符
- powershell - 无法让 sharepoint powershell 管理员工作 - 术语无法识别
- keras - 如何使用 ImageDataGenerator flow_from_directory 以原始名称作为前缀保存增强图像
- amazon-web-services - 我可以分配给 AWS 上的自定义策略的最大权限数是多少?
- javascript - 无法翻译卡信息 Square 最新 Magneto 扩展
- html - 更改 div _rmc 值
- python - 如何在“ngroups”期间重置索引以按列显示组?
- footer - Birt Master Footer - 动态设置数据不工作 eclipse 4.3.1 (Maximo 7.6.1.1 - BIRT)