【发布时间】:2018-11-15 07:37:06
【问题描述】:
我想在我的本地项目文件夹中生成一个 .json 文件。我想将 fetch 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 code 中运行代码时,出现以下错误:
undefined 不是函数('...fs.writeFileSync...' 附近)
似乎是因为在创建json文件时数据还没有准备好(异步)。一些网站推荐使用 setTimeOut 函数或 sf.writeFileSync 而不是 sf.writeFile。我都试过了,但还是不行。 你能帮我解决这个问题吗? 非常感谢
【问题讨论】:
标签: javascript