Skip to content
Advertisement

Convert response to JSON/String and Write to a File

I’m new on java and node, so after 2 days trying to do this… i wrote this question.

I’m using a git (https://github.com/gigobyte/HLTV) and trying to make files with the responses i get from this api, but all i got so far is to write the results in the console.

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!')

Is there any way to convert it directry and write a file with the string?

Advertisement

Answer

you have to do it in the then call

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');
  });
});
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement