繁体   English   中英

node.js如何使用fs接收get api结果

[英]node.js how to use fs for received get api result

我是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);
}
});

三个问题:

1-temp和response.body都在fetch()函数内,因此不能在外部使用。

2-您对异步操作的处理不正确。 尽管setInterval将延迟获取10秒钟,但是写入文本文件仍将立即运行。

3-您正在文件末尾使用异步文件写入方法。 IIRC程序将在完成之前终止。

一个简单的解决方案是在外部获取中创建一个变量来存储值,运行获取,然后将写入操作延迟10秒。

但是,在继续操作之前,等待任意时间等待异步操作完成是不理想的。

如果您愿意使用ES2017 / ES8,请提出以下代码:

const got = require('got');
const fs = require('fs');

async function fetch() {
  const response = await got('https://www.google.com');
  return response.body;
};

fetch().then(body => fs.writeFileSync('./demo3.txt', body));

(PS!我从get。中删除了选项{json:true},因为据我所知,google.com似乎只会返回html。不确定这对您尝试执行的操作是否重要。)

如果您不熟悉语法:

异步-声明异步操作。 可以很容易地用作Promise(在文件末尾完成)或Observable。

await-告诉程序停止执行代码,直到解决了同一行上的异步操作为止。 在这种情况下,操作会等待google.com的回复

writeFileSync-将其从写入更改为确保处理器在终止之前等待进程完成。 根据您在何种情况下运行该程序,这可能需要也可能没有必要。

当您不熟悉NodeJS时,您需要了解回调函数的概念。 这里的“ get”是一个回调函数。 与其他类型的脚本不同,NodeJ不会等待提取完成,而是会继续前进并执行其余语句。 您的代码有一些错误。

  1. 变量“ temp”,“ response”的作用域。 -在执行fs.write时,response.body仍未定义和声明。 由于提取功能尚未执行。

  2. 您发送了一个参数{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格式的。

function fetch(){
   var fs = require('fs');
   var got = require('got');

    got('https://www.google.com', { json: true }).then(response => {

    console.log(response.body);
    temp = response.body;
     fs.writeFile("/tmp/test",temp, function(err) {
        if(err) {
            return console.log(err);
        }
        console.log("The file was saved!");
    });

    }).catch(error => {
       console.log(error.response.body);
    });
};    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM