簡體   English   中英

如何使用fs.writeFile從訪存API調用響應中創建.json文件

[英]How to create a .json file from fetch API call response using fs.writeFile

我想在本地項目文件夾中生成一個.json文件。 我想將提取API調用響應(是一個對象數組)保存到硬盤上的.json文件中。 這是我的代碼:

const fs = require('fs');

導出默認函數getdirectory(token){

return fetch(url, {
                  headers: {Authorization: "Bearer " + token}
                })
                .then((response) => response.json())
                .catch((err) =>{
                    console.log("ERORRRRRRRR @@@@@@" + err);
                })
                .then((response) =>   { 
                    //console.log(response);
                    var jsoncontent = JSON.stringify(response);
                    //console.log(jsoncontent);
                    fs.writeFileSync('files-to-cache.json', jsoncontent, function(err) {

                    if (err) 
                        {console.log("EROROROROROR ****" + err);}
                    else
                        { return response;}
                    });
                   // return response;
                })
                .catch((err) =>{
                    console.log("ERORRRRRRRR $$$$$$" + err);
                })
            };

當我在vs代碼中運行代碼時,出現以下錯誤:

未定義不是函數(在'... fs.writeFileSync ...'附近)

似乎發生這種情況是因為在創建json文件時(異步)數據還沒有准備好。 一些網站建議使用setTimeOut函數或sf.writeFileSync而不是sf.writeFile。 我都嘗試過,但仍然行不通。 您能幫我解決這個問題嗎? 非常感謝

您使用的是錯誤版本的寫入文件,有兩種不同的類型,請參見下文:

第一個是writeFileSync,它是同步的,並且將阻塞線程,這意味着您的腳本在完成之前無法繼續,但最重要的是它不接受回調。

嘗試以下方法:

  fs.writeFile('data.json', jsonData, 'utf8', (err) => {
    if (err) throw err
    console.log('File created!`)
  })

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM