首页 > 解决方案 > 将响应转换为 JSON/String 并写入文件

问题描述

我是java和node的新手,所以在尝试了2天之后......我写了这个问题。

我正在使用 git ( https://github.com/gigobyte/HLTV ) 并尝试使用从该 api 获得的响应来制作文件,但到目前为止我所得到的只是将结果写入控制台。

import HLTV from './index'
const fs = require('fs');
function sleep(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms))
}

sleep (1000)
//HLTV.getPlayerByName({ name: "chrisJ" }).then(res => this.Teste = res );
var Text = HLTV.getMatches().then(data => {console.log(JSON.stringify(data)); })
//var Texto = HLTV.getTeamRanking({ country: 'Brazil' });
//then(data => { console.log(JSON.stringify(data)); })
sleep(3000)
fs.writeFileSync('MyFile.json', Text)
console.log('Scoreboard update!')

有没有办法直接转换它并用字符串写一个文件?

标签: javascriptjavajson

解决方案


你必须在then通话中这样做

HLTV.getMatches().then(data => {
  var txt = JSON.stringify(data);
  fs.writeFile('MyFile.json', txt, function (err) {
    if (err) return console.log(err);
    console.log('Data Saved');
  });
});

推荐阅读