Skip to content
DeveloperMemos

How to Read a CSV File with Deno

Deno, CSV, File Handling, JavaScript, TypeScript1 min read

Deno, the secure runtime for JavaScript and TypeScript, continues to evolve with new features and improvements. Among its many functionalities, Deno provides a straightforward way to read CSV (Comma-Separated Values) files, a common data format used for storing tabular data.

Setting Up Deno

Before we begin, ensure that you have Deno installed on your system. You can install Deno by following the instructions on the official Deno website.

Once Deno is installed, create a new TypeScript file for your Deno project. For this tutorial, let's name it read_csv.ts.

Example CSV File

Let's start with an example CSV file that we'll use for demonstration purposes. Below is a Markdown representation of the CSV file:

NameAgeGenderOccupation
John30MaleSoftware Eng
Alice25FemaleData Scientist
Bob35MaleWeb Developer
Emily28FemaleUX Designer

Save this table to a file named data.csv in your project directory.

Reading the CSV File

Deno provides various built-in modules and supports third-party modules from a variety of sources. In this example, we'll use jsr:@std/csv to parse the CSV file:

1// Importing necessary modules
2import { parse } from "jsr:@std/csv";
3
4// Function to read CSV file
5async function readCSV(filePath: string) {
6 // Open the CSV file as text
7 const data = await Deno.readTextFile(filePath);
8
9 // Parse the CSV content
10 const records = parse(data, {
11 skipFirstRow: true, // Skip header row if present
12 });
13
14 // Return parsed CSV data
15 return records;
16}
17
18// Usage example
19const filePath = "data.csv";
20const csvData = await readCSV(filePath);
21console.log(csvData);

Explanation

  • We import the parse function from the jsr:@std/csv module. This module can parse CSV data.
  • The readCSV function takes a file path as input, reads the CSV file as text using Deno.readTextFile, and then parses the CSV content using the parse function.
  • In the usage example, we specify the file path (data.csv in this case) and call the readCSV function to read the CSV file.

Handling CSV Data

Once the CSV data is parsed, you can manipulate it according to your requirements. For instance, you might want to perform data processing, filtering, or analysis.


Reading a CSV file with Deno is a straightforward process, especially with modules like jsr:@std/csv. By following the steps outlined in this tutorial, you can efficiently read CSV files in your Deno projects and leverage the data for your own purposes!