简体   繁体   English

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

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

I'm a newbie at node.js. 我是node.js的新手。 here I'm trying to create a txt file with my received result(response.body). 在这里,我试图用接收到的结果(response.body)创建一个txt文件。 but it just prints an exception. 但是它只是打印一个异常。 need your kind help. 需要您的帮助。

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

Three problems: 三个问题:

1 - temp and response.body are both scoped within your fetch() function, and therefore cannot be used outside. 1-temp和response.body都在fetch()函数内,因此不能在外部使用。

2 - your handling of async operations is incorrect. 2-您对异步操作的处理不正确。 While setInterval will delay the fetch by 10 seconds, the writing to the text file will still run immediately. 尽管setInterval将延迟获取10秒钟,但是写入文本文件仍将立即运行。

3 - you are using the async file writing method at the end of the file. 3-您正在文件末尾使用异步文件写入方法。 IIRC the program will terminate before this can complete. IIRC程序将在完成之前终止。

A naive solution would be to make a variable outside fetch for storing the value, running fetch, and then having the writing operation delayed by 10 seconds. 一个简单的解决方案是在外部获取中创建一个变量来存储值,运行获取,然后将写入操作延迟10秒。

However it is not ideal to wait an arbitrary amount of time for an async operation to finish before proceeding. 但是,在继续操作之前,等待任意时间等待异步操作完成是不理想的。

If you're willing to use ES2017/ES8 I propose the following code: 如果您愿意使用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! I removed the option {json:true} from got as google.com seems to only return html as far as I could tell. Not sure if this was important to whatever it is you were trying to do.) (PS!我从get。中删除了选项{json:true},因为据我所知,google.com似乎只会返回html。不确定这对您尝试执行的操作是否重要。)

In case you're unfamiliar with the syntax: 如果您不熟悉语法:

async - declares an async operation. 异步-声明异步操作。 It is straightforward to use as either a Promise (as done at the end of the file) or Observable. 可以很容易地用作Promise(在文件末尾完成)或Observable。

await - tells the program to halt execution of code until the async operation on the same line has resolved. await-告诉程序停止执行代码,直到解决了同一行上的异步操作为止。 In this case, operation waits for a response from google.com 在这种情况下,操作会等待google.com的回复

writeFileSync - Changed this from write to make sure the processor waits for the process to finish before terminating. writeFileSync-将其从写入更改为确保处理器在终止之前等待进程完成。 This might or might not be necessary depending on under which circumstances you are running this program. 根据您在何种情况下运行该程序,这可能需要也可能没有必要。

as you are new to nodeJS, you need to know to concepts of callback functions. 当您不熟悉NodeJS时,您需要了解回调函数的概念。 Here 'got' is a callback function. 这里的“ get”是一个回调函数。 Unlike other types of scripts, NodeJs won't wait for fetch to get completed, rather it will move forward and execute the remaining statements. 与其他类型的脚本不同,NodeJ不会等待提取完成,而是会继续前进并执行其余语句。 Your code has got a few mistakes. 您的代码有一些错误。

  1. Scoping of variables 'temp', 'response'. 变量“ temp”,“ response”的作用域。 -- At the time of execution of fs.write, the response.body remains undefined and undeclared. -在执行fs.write时,response.body仍未定义和声明。 As fetch function didn't get executed yet. 由于提取功能尚未执行。

  2. You sent a parameter { json: true }, this parameter tries to get the response in JSON format. 您发送了一个参数{json:true},该参数尝试获取JSON格式的响应。 But the requested URL replies with a normal text document / HTML document. 但是,所请求的URL用普通的文本文档/ HTML文档答复。 So removing that parameter will surely help. 因此,删除该参数肯定会有所帮助。

     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(); 

Here fs.write will execute after the 'got' function completes its execution by returning response variable. fs.write将在“ got”函数通过返回响应变量完成其执行之后执行。 Here I have also removed the parameter { json: true } , as the response is not in JSON format. 在这里,我还删除了参数{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