簡體   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