Skip to content

Instantly share code, notes, and snippets.

@jayperryworks
Created January 26, 2021 17:53
Show Gist options
  • Save jayperryworks/5fbe47b1f3c14c826eee5d25eda2015f to your computer and use it in GitHub Desktop.
Save jayperryworks/5fbe47b1f3c14c826eee5d25eda2015f to your computer and use it in GitHub Desktop.
Fetch API data with node.js
// To run this:
// 1. download these files
// 2. run `npm install`
// 3. run `npm run test`
// 4. see if a `data.json` file was written
// https://github.com/node-fetch/node-fetch
const fetch = require('node-fetch')
const fs = require('fs')
// fetch returns a promise so we need it inside an async function
async function query (url) {
try {
const response = await fetch(url)
// possibly don't need json() call here, as we won't be working with the data programmatically but just dumping the string into a file
const data = await response.json()
return data
} catch (error) {
console.log(`Oh no! ${response.status}: ${error}`)
}
}
query('https://jsonplaceholder.typicode.com/posts/1').then((data) => {
fs.writeFile('data.json', JSON.stringify(data), (error) => {
if (error) throw error
})
})
{
"name": "fetch-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"fetch": "node ./fetch.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"node-fetch": "^2.6.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment