Skip to Content

Fetching data

By Nael Shiab

Last updated on

The Web is ubiquitous and an extraordinary source of data. In this lesson, we’ll explore how to fetch and download data.

I assume you’ve completed Chapter 1 and all previous lessons in Chapter 2 before diving into this one. In particular, make sure you’ve followed the Setup lesson.

Want to know when new lessons are available? Subscribe to the newsletter ✉️ and give a ⭐ to the GitHub repository to keep me motivated! Click here to get in touch.

Setup

Create a new, empty folder on your computer, open it with VS Code, and create a file named main.ts inside it.

Type this code in main.ts and save the file:

main.ts
console.log("Hello!");

Open the terminal (Command + J on Mac or Control + J on Windows) and run this command:

node --watch main.ts

This runs our code and automatically runs it again each time we save a change, so we can see the results as we work.

VS Code showing console.log("Hello!") in main.ts and Hello! in the terminal running node --watch main.ts.

Fetching a JSON file

Let’s fetch this temp.json  file. It contains the daily temperatures in Montreal from 2000 to 2020. I uploaded it to GitHub specifically for this lesson.

If you open it, you’ll notice it’s an array of objects, with each object storing a date string and a temperature.

A screenshot showing VS Code running and watching a TypeScript file.

To fetch it, you can use the fetch() function. It’s globally available, so you can call it directly in your code. It requires the relevant URL as a string.

main.ts
// @ts-ignore const response = await fetch( "https://raw.githubusercontent.com/nshiab/data-fetch-lesson/refs/heads/main/temp.json", ); console.log(response);
💡

You might be wondering what // @ts-ignore means. It tells VS Code to ignore type errors on the next line. I added it because calling fetch with await this way requires some extra setup for TypeScript. I don’t want to bother you with that yet: for now, I just want you to focus on fetch.

As you can see in the code above, fetch() is an asynchronous function, and we use await to wait for its result.

As we saw in the Writing and reading files lesson, synchronous functions finish their work before the next instruction runs. Asynchronous functions let an operation continue while the code moves on. Here, await makes our code wait for the response before logging it.

Having fetch() work asynchronously is extremely useful: you can start fetching several files concurrently instead of waiting for each one to finish before starting the next. Letting those requests run in parallel can make your script much faster.

If you hover over fetch in VS Code, you’ll see that it returns a Promise<Response>. A promise represents a result that will be available later; await lets us get that result when it’s ready.

VS Code showing the fetch hover documentation with a Promise of a Response as its return type.

Now, let’s focus on what’s in the terminal. As you can see, there is a lot of stuff in this response, and that’s normal. Your computer and the server hosting the file exchange a lot of information to ensure the connection works properly.

In our case, we know the content we’re after is a JSON file, so we can call the .json() asynchronous method to parse the response data as JSON.

main.ts
// @ts-ignore const response = await fetch( "https://raw.githubusercontent.com/nshiab/data-fetch-lesson/refs/heads/main/temp.json", ); // @ts-ignore const data = await response.json(); console.log(data);

VS Code showing response.json() parsing the fetched response and the temperature data logged in the terminal.

Here we go! We’ve fetched the data, and now we can work with it!

Instead of fetching it every time, we could write the data to a file for future use.

main.ts
// @ts-ignore import { writeFile } from "node:fs/promises"; const response = await fetch( "https://raw.githubusercontent.com/nshiab/data-fetch-lesson/refs/heads/main/temp.json", ); const data = await response.json(); await writeFile("./temp.json", JSON.stringify(data));

VS Code showing writeFile saving the fetched temperature data to temp.json, with the JSON file open beside the script.

Congrats! You now know how to fetch and save JSON files. That was easy, wasn’t it? 😄

Fetching a text/CSV file

Instead of JSON, you might want to fetch and save a CSV file, which is plain text.

It’s pretty straightforward: instead of calling .json() to parse the response, use .text().

I uploaded temp.csv  on GitHub for this lesson.

Here’s the updated code to fetch and write it. We’ll explore how to crunch CSV file data in another lesson.

main.ts
// @ts-ignore import { writeFile } from "node:fs/promises"; const response = await fetch( "https://raw.githubusercontent.com/nshiab/data-fetch-lesson/refs/heads/main/temp.csv", ); const data = await response.text(); await writeFile("./temp.csv", data);
💡

To write the JSON data, we had to use JSON.stringify() because here writeFile needs text rather than an array, and the JSON data was an array of objects. However, the CSV data is already text, so we can pass it directly to writeFile.

VS Code showing response.text() reading the fetched CSV and writeFile saving it to temp.csv, open beside the script.

Fetching a webpage HTML

You can also fetch the source code of a webpage. For example, here’s how to retrieve the HTML from the Code Like a Journalist homepage.

main.ts
// @ts-ignore const response = await fetch( "https://www.code-like-a-journalist.com/en", ); // @ts-ignore const html = await response.text(); console.log(html);

VS Code showing fetch retrieving the homepage HTML and logging it in the terminal.

Conclusion

You now know how to fetch and save data with Node.js.

But there’s something else that is extremely useful and published on the Web: TypeScript libraries. Go check out the next lesson to discover what they are! 👀

Enjoyed this? Want to know when new lessons are available? Subscribe to the newsletter ✉️ and give a ⭐ to the GitHub repository to keep me motivated! Get in touch if you have any questions.