Downloading JSON data from a REST API and writing it to a file in NodeJS
It's one common use case to read data from an API source and writing the data into a JSON file in the disk. The following code shows you how to do that in NodeJS. It uses an npm library 'node-fetch' for making an HTTP call.
const fetch = require('node-fetch');
var fs = require('fs');
async function getAndWriteData(url, filePath){
let res = await fetch(url)
let data = await res.json();
fs.writeFileSync(filePath, JSON.stringify(data));
}
// calling the util function
getAndWriteData('https://jsonplaceholder.typicode.com/todos', '/path/to/some/folder/data.json');